pull解析xml格式的InputStream遇到的问题
问题描述:
org.xmlpull.v1.XmlPullParserException: Premature end of document. (position:line -1, column -1) caused by: org.apache.harmony.xml.ExpatParser$ParseException: At line 1, column 0: no element found
此问题困扰了我一下午,在实际的开发中我们发送请求访问服务器端,当返回的是xml格式的InputStream对象时,有时我们采用解析方法如sax,pull 对流进行解析时会出现上面的情况,显示解析,这时可以将流对象读取到内存中转换成字符串,在以流的方式从内存中读出。重新解析就可以得到正确的对象集合。
1、将输入流读成二进制数据。
public static byte[] readInputStream(InputStream inStream) throws Exception{ ByteArrayOutputStream outSteam = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while( (len = inStream.read(buffer)) !=-1 ){ outSteam.write(buffer, 0, len); } outSteam.close(); inStream.close(); return outSteam.toByteArray(); }
2、将字符串转换成流再传入到pull解析流程中
XmlPullParser parser = Xml.newPullParser(); String mm=new String(StreamTool.readInputStream(inStream)); Log.i("main", "进入parsexml方法2"+mm); //parser.setInput(inStream,"UTF-8"); Log.i("abc", mm); ByteArrayInputStream byte1=new ByteArrayInputStream(mm.getBytes()); parser.setInput(byte1,"UTF-8");