2014-01-29 87 views
2

我使用以下兩種方法來解析我的XML數據:

private static XMLReader prepareSAX() throws ParserConfigurationException, 
     SAXException { 
    SAXParserFactory spf = SAXParserFactory.newInstance(); 
    SAXParser sp = spf.newSAXParser(); 

    return sp.getXMLReader(); 
} 
public static void LectorSAX(XMLReader xr, String url) { 
    try { 

     InputSource is = new InputSource(url); 
     is.setEncoding("UTF-8"); 
     xr.parse(is); 
    } catch (SAXException e) { 
     System.err.println("Error de sax LectorSAX.java: " + e); 
     e.printStackTrace(); 
    } catch (IOException e) { 
     System.err.println("Error de io LectorSAX.java: " + e); 
     e.printStackTrace(); 
    } 
} 

現在我的XML數據如下:

<Product> 
<Product_ID>22434</Product_ID> 
<Chinese_Name>三Q 逆齡速效霜</Chinese_Name> 
<English_Name>Q10 QUICK GEL MOIST & WHITENING</English_Name> 
<Image_Path>http://www.abc.com/prodImage/dtl/13011015,38,8.jpg</Image_Path> 
<Original_Price>880</Original_Price> 
<Discounted_Price>0</Discounted_Price> 
<Product_Detail><![CDATA[<html><body>三Q 逆齡速效霜</br>Q10 QUICK GEL MOIST & WHITENING<br><br></body></html>]]></Product_Detail> 
</Product> 

我得到的關注Exeption:

01-29 04:14:10.637: W/System.err(1665): Error de sax LectorSAX.java: org.apache.harmony.xml.ExpatParser$ParseException: At line 185, column 36: unknown encoding 
01-29 04:14:10.758: W/System.err(1665):  at org.apache.harmony.xml.ExpatParser.parseFragment(ExpatParser.java:515) 
01-29 04:14:10.758: W/System.err(1665):  at org.apache.harmony.xml.ExpatParser.parseDocument(ExpatParser.java:474) 
01-29 04:14:10.758: W/System.err(1665):  at org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:321) 
01-29 04:14:10.818: W/System.err(1665):  at org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:294) 
01-29 04:14:10.818: W/System.err(1665):  at com.dhc.xmlparsing.XMLParser.LectorSAX(XMLParser.java:79) 

我的第185行English_Name標籤。 所以我在做錯了,請幫助我。

+0

複製粘貼,這裏185行包含標籤 – Naren

+0

不needed..friend..got一個solution.thanks – Kishan

回答

8

終於找到了解決方法,它是saxParser編碼「&」(特殊字符)的問題,所以我用&amp;替換了「&」。現在它的工作完美,代碼如下所示:

response = response.replaceAll("&", "&amp;"); 
    InputSource inputSource = new InputSource(); 
    inputSource.setEncoding("UTF-8"); 
    Log.i("TAG", "response" + response); 
    inputSource.setCharacterStream(new StringReader(response)); 
    xr.parse(inputSource); 
+0

感謝您的知識共享和驗證碼我有幫助,並刪除警告以及例外.. 。! :) –

+0

Thanx工作像魅力! – Debasish

+0

在 字符事件段添加一些文件,oracle網站https://docs.oracle.com/javase/tutorial/jaxp/sax/parsing.html –

1

我也面臨同樣的問題在我的代碼中,我嘗試了下面的解決方案。它爲我工作。

InputSource inputSource = new InputSource(); 
inputSource.setEncoding("ISO-8859-1"); 
inputSource.setCharacterStream(new StringReader(response)); 
xr.parse(inputSource);