package com.qmth.qrzk.repository.utils;

public class XML {
	/**
	 * 检查字符是否为合法的xml字符
	 * XML规范中规定了允许的字符范围(http://www.w3.org/TR/REC-xml#dt-character): 
	 * Char ::= #x9| #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
	 * 
	 * @param ch
	 * @return
	 */
	public static boolean isLegalXMLCharacter(int ch) {
		if (ch <= 0xD7FF) {
			if (ch >= 0x20) {
				return true;
			} else {
				return ch == '\n' || ch == '\r' || ch == '\t';
			}
		}else{
			return (ch >= 0xE000 && ch <= 0xFFFD) || (ch >= 0x10000 && ch <= 0x10FFFF);
		}
	}
	/**
	 * 去掉xml字符串中的非法字符
	 * 
	 * @param xml
	 * @return
	 */
	public static String removeIllegalXmlCharacters(String xml) {
		if (xml == null || xml.length() <= 0) {
			return "";
		}
		int len = xml.length();
		StringBuilder sb = new StringBuilder(len);
		for (int i = 0; i < len; i++) {
			char ch = xml.charAt(i);
			if (isLegalXMLCharacter(ch)) {
				sb.append(ch);
			}
		}
		return sb.toString();
	}

}
