2010-03-02 48 views
11

無效XML字符解析Java的XML文件,我得到的錯誤:錯誤有關的Java

An invalid XML character (Unicode: 0x0) was found in the element content of the document.

的XML來自一個web服務。

問題是,只有當webservice運行在本地主機(windows + tomcat)上,而不是web服務在線時(linux + tomcat),我纔會得到錯誤。

我該如何更換無效字符? 謝謝。

回答

7

固定與此代碼:保存到MySQL

String cleanXMLString = null; 
Pattern pattern = null; 
Matcher matcher = null; 
pattern = Pattern.compile("[\\000]*"); 
matcher = pattern.matcher(dirtyXMLString); 
if (matcher.find()) { 
    cleanXMLString = matcher.replaceAll(""); 
} 
+3

+1,但可以通過'dirtyXMLString.replaceAll(「[\\ 000] *」,「」)'簡化。 – sp00m 2013-10-17 12:34:19

+2

也可以通過將'*'改成'+'加速:'dirtyXMLString.replaceAll(「[\\ 000] +」,「」)'' – Whitecat 2015-06-29 17:38:25

4

這是一個編碼問題。你可以將它看作是UTF8的輸入流,而不是或者相反。

您應該在閱讀內容時明確指定編碼。例如。通過

new InputStreamReader(getInputStream(), "UTF-8") 

另一個問題可能是tomcat。嘗試在server.xml文件的tomcat連接器設置中添加URIEncoding =「UTF-8」。因爲:

It turned out that the JSP specification says that if the page encoding of the JSP pages is not explicitely declared, then ISO-8859-1 should be used (!).

摘自here

+0

性格像這樣http://www.fileformat.info/info/unicode/char/e4f8/index.htm失敗。有沒有一種通用的方式來查找或忽略這些在java中。添加「UTF-8」沒有幫助。 – titogeo 2013-12-20 07:22:27

11

Unicode字符0x0代表NULL這意味着您正在提取的數據在某處包含NULL(這在XML中是不允許的,因此也是錯誤)。

確保您首先找出導致NULL的原因。

另外,你如何與WebService進行交互?如果您使用的是Axis,請確保WSDL具有爲數據輸入和輸出指定的一些編碼。

+2

+1常識方法。盲目修復這種錯誤而不關心它來自哪裏並不是一個好主意。 – Tomalak 2010-03-02 13:01:41