Dom4j 读 xml 时,遇到 xml 无效字符,报错:An invalid XML character
版权信息: 可以任意转载, 转载时请务必以超链接形式标明文章原文出处, 即下面的声明.
原文出处:http://blog.chenlb.com/2008/11/an-invalid-xml-character-on-dom4j-read-xml-file.html
读xml时,经常遇到无效字符,dom4j就抛出异常。今天我又遇到了,用dom4j读xml时,报:An invalid XML character (Unicode: 0x1d) was found in the CDATA section.
它说xml有无效字符,然后找一下,xml 的无效字符有那些,它有三段,官方定义的无效字符为:
- 0x00 - 0x08
- 0x0b - 0x0c
- 0x0e - 0x1f
下面用JAVA过虑这些字符。
- package com.chenlb;
- public class XmlUtil {
- /**
- * 过虑xml的无效字符。<p/>
- * <ol>
- * <li>0x00 - 0x08</li>
- * <li>0x0b - 0x0c</li>
- * <li>0x0e - 0x1f</li>
- * </ol>
- * @author chenlb 2008-11-7 下午04:27:48
- */
- public static String filter(String xmlStr) {
- StringBuilder sb = new StringBuilder();
- char[] chs = xmlStr.toCharArray();
- //System.out.println("filter before=" +chs.length);
- for(char ch : chs) {
- if((ch >= 0x00 && ch <= 0x08)
- || (ch >= 0x0b && ch <= 0x0c)
- || (ch >= 0x0e && ch <= 0x1f)) {
- //eat...
- } else {
- sb.append(ch);
- }
- }
- //System.out.println("filter after=" +sb.length());
- return sb.toString();
- }
- }