2017-03-13 85 views
0

我有一個XML格式的SoapMesagge,其中包含中文字符。使用Java解析中文字符拋出org.xml.sax.SAXParseException; lineNumber:1; columnNumber:1;內容不允許在序言中

<?xml version="1.0" encoding="UTF-8"?> 
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
<soapenv:Body> 
<new:NewOperation xmlns:new="http://www.example.org/NewWSDLFile/"> 
    <in>4) 軟件應安全、。</in> 
</new:NewOperation> 
</soapenv:Body> 
</soapenv:Envelope> 

解析這個我寫了下面的代碼在JAVA其中的SOAPMessage是我的消息

ByteArrayInputStream is = new ByteArrayInputStream(soapMessage.getBytes()); 
InputStreamReader isr = new InputStreamReader(is,"UTF-8); 
InputSource source=new InputSource(isr); 
SAXParser parser = new SAXParser(); 
parser.parse(source); 

這是不能分析中國焦炭和投擲以下錯誤,請幫我解決這個問題。

Fatal Error] :1:1: Content is not allowed in prolog. 
org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog. 
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source) 

我也嘗試過與Dom Parser以及。

+1

檢查XML沒有一個BOM:https://en.wikipedia.org/wiki/Byte_order_mark。 – Berger

+0

感謝您的更新,我已經嘗試使用下面的代碼'String s = soapMessage.replaceFirst(「^ \ uFEFF」,「」);'但是我所有的中國char變成了???這種字符串。 '<新:NewOperation的xmlns:新= 「http://www.example.org/NewWSDLFile/」> 4)\t ????? ' –

+0

你在哪裏看到的''????在控制檯?也許它無法打印這些字符。嘗試在新文件中輸出值並檢查其內容,或者僅打印每個讀取字符的int值以確保它們不是'?'字符。 – Berger

回答

0

你能請檢查下面的鏈接,一個回答是已經提到的,可以幫助你。

parsing chinese characters in java showing weird behaviour

而且我覺得你的代碼在編譯時有如下錯誤也失敗:

代碼:SAXParser parser = new SAXParser();

錯誤:Cannot instantiate the type SAXParser

因爲的SAXParser是一個抽象類你不能直接實例化:

public abstract class javax.xml.parsers.SAXParser 
相關問題