解析UTF-8编码的XML文件

我有一个XML文件,其中包含从URL检索到的一些阿拉伯字符,所以我必须用UTF-8对其进行编码,以便它可以处理这些字符。

XML文件:

   1 News Test 1 16/7/2012 joelle.mobi-mind.com/imgs/news1.jpg   2 كريم 16/7/2012 joelle.mobi-mind.com/imgs/news2.jpg   3 News Test 333 16/7/2012 joelle.mobi-mind.com/imgs/news3.jpg   4 ربيع 16/7/2012 joelle.mobi-mind.com/imgs/cont20.jpg   5 News Test 55555 16/7/2012 joelle.mobi-mind.com/imgs/cont21.jpg   6 News Test 666666 16/7/2012 joelle.mobi-mind.com/imgs/cont22.jpg    

我将从URL检索到的XML解析为String,如下所示:

 public String getXmlFromUrl(String url) { try { return new AsyncTask() { @Override protected String doInBackground(String... params) { //String xml = null; try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet httpPost = new HttpGet(params[0]); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); xml = new String(EntityUtils.toString(httpEntity).getBytes(),"UTF-8"); } catch (Exception e) { e.printStackTrace(); } return xml; } }.execute(url).get(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } return xml; } 

现在返回的String被传递给此方法以获取Document以供以后使用,如下所示:

 public Document getDomElement(String xml){ Document doc = null; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); StringReader xmlstring=new StringReader(xml); is.setCharacterStream(xmlstring); is.setEncoding("UTF-8"); //Code Stops here ! doc = db.parse(is); } catch (ParserConfigurationException e) { Log.e("Error: ", e.getMessage()); return null; } catch (SAXException e) { Log.e("Error: ", e.getMessage()); return null; } catch (IOException e) { Log.e("Error: ", e.getMessage()); return null; } // return DOM return doc; } 

使用此消息发生错误:

 09-18 07:51:40.441: E/Error:(1210): Unexpected token (position:TEXT @1:4 in java.io.StringReader@4144c240) 

所以代码崩溃我在上面显示的地方有以下错误

 09-18 07:51:40.451: E/AndroidRuntime(1210): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.university1/com.example.university1.MainActivity}: java.lang.NullPointerException 

请注意,代码适用于ISO编码。

您已在UTF-8文件中添加了BOM 。 这很糟糕。

也许您使用记事本编辑了文件,或者您应该检查编辑器以确保它不添加BOM。

由于BOM似乎在文本内部而不是在开始时,您还需要通过在其位置周围使用删除键来删除它(在大多数编辑器中它是不可见的)。 这可能发生在文件串联操作期间。

这可能不是问题,但EntityUtils.toString(httpEntity).getBytes()正在使用默认的平台编码。 您应该使用EntityUtils.toString(httpEntity)作为String ,无需将其转换为字节。

另外,请阅读此http://kunststube.net/encoding/ ,了解有关正在发生的事情的有用背景。