2012-08-03 105 views
1

我有一个由UTF-16编码的字符串。当使用javax.xml.parsers.DocumentBuilder分析,我得到了这样的错误:如何替换XML字符串中的无效字符?

Character reference "&#x0" is an invalid XML character 

这里是我用来解析XML代码:

InputSource inputSource = new InputSource(); 
inputSource.setCharacterStream(new StringReader(xmlString)); 
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
DocumentBuilder parser = factory.newDocumentBuilder(); 
org.w3c.dom.Document document = parser.parse(inputSource); 

我的问题是,如何通过替换无效字符(空间)?

+4

您必须这么做*您解析XML之前。 – 2012-08-03 14:13:50

+0

我知道我必须在解析之前做到这一点,但问题是怎么做? – user1574322 2012-08-03 14:18:15

+1

从另一个stackoverflow线程检查此答案:http://stackoverflow.com/a/4237934/405117 – Vikram 2012-08-03 14:18:34

回答

0

您试图解析无效的xml entity,这是引发异常的原因。看来你不必为你的情况担心UTF-16

查找一些解释和示例here

作为一个例子,不能使用&字符,我们需要使用&来替代。这里&是xml实体。

假设上面的例子应该是自我解释的,以了解xml实体是什么。

据我所知有一些XML无效的实体。但不用担心。有可能宣布&增加新的xml entity。看看上面的文章了解更多细节。


编辑:假设有&性格使XML无效。

1

你只需要使用String.replaceAll并传递无效字符的模式。

+0

我的xmlString是这样的: <?xml version =“1.0”encoding =“utf-16”?> 这是我的内容    � �  � 是什么模式? 谢谢 – user1574322 2012-08-03 15:34:36

0

StringEscapeUtils()

将escapeXml

public static void escapeXml(java.io.Writer writer, 
          java.lang.String str) 
         throws java.io.IOException 

Escapes the characters in a String using XML entities. 

For example: "bread" & "butter" => &quot;bread&quot; &amp; &quot;butter&quot;. 

Supports only the five basic XML entities (gt, lt, quot, amp, apos). 
Does not support DTDs or external entities. 

Note that unicode characters greater than 0x7f are currently escaped to their 
numerical \\u equivalent. This may change in future releases. 

Parameters: 
    writer - the writer receiving the unescaped string, not null 
    str - the String to escape, may be null 
Throws: 
    java.lang.IllegalArgumentException - if the writer is null 
    java.io.IOException - if there is a problem writing 
See Also: 
    unescapeXml(java.lang.String)