2012-08-03 104 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)