Java 怎么将空XML标记追加到给定的StringBuffer

2019年8月3日23:29:37Java 怎么将空XML标记追加到给定的StringBuffer已关闭评论 462 1315字阅读4分23秒

1.简介

Java 怎么将空XML标记追加到给定的StringBuffer?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */

import java.util.Map;
import java.util.Map.Entry;

public class Main{
    
    public static final String LEADING_WHITE_SPACE_PER_LEVEL = "   ";
    
    public static void appendEmptyTag(int level, String tagName,
            Map<String, String> attributeValues, StringBuffer sb) {
        appendWhiteSpace(level, sb);
        sb.append("<");
        sb.append(tagName);
        for (Entry<String, String> entry : attributeValues.entrySet()) {
            appendAttribute(entry.getKey(), entry.getValue(), sb);
        }
        sb.append("/>");
        appendNewLine(sb);
    }
    
    public static void appendWhiteSpace(int level, StringBuffer sb) {
        for (int i = 0; i < level; i++) {
            sb.append(LEADING_WHITE_SPACE_PER_LEVEL);
        }
    }
    
    public static void appendAttribute(String attributeName, String value,
            StringBuffer sb) {
        if (attributeName != null && value != null) {
            sb.append(" ");
            sb.append(attributeName);
            sb.append("=\"");
            sb.append(XMLUtil.encodeText(value));
            sb.append("\"");
        }
    }
    
    public static void appendNewLine(StringBuffer sb) {
        sb.append(StringUtil.NEW_LINE);
    }
    
    public static String encodeText(String text) {
        if (text != null) {
            char[] signs = text.toCharArray();
            StringBuffer sb = new StringBuffer();
            for (char sign : signs) {
                switch (sign) {
                case '"':
                    sb.append(""");
                    break;
                case '&':
                    sb.append("&");
                    break;
                case '\'':
                    sb.append("'");
                    break;
                case '<':
                    sb.append("<");
                    break;
                case '>':
                    sb.append(">");
                    break;
                default:
                    sb.append(sign);
                    break;
                }
            }
            return sb.toString();
        } else {
            return null;
        }
    }
}

 
继续阅读
编程十万个怎么办