问题
I'm trying to parse an xml document using the xml pull parser. Everything worked fine until i started dealing with an xml document containing an xxml declartation:
When the declaration is there i get the following error:
02-08 15:37:16.960: WARN/System.err(9721): org.xmlpull.v1.XmlPullParserException: PI must not start with xml (position:unknown @1:5 in java.io.InputStreamReader@47ec2770)
If I take out the declaration from the document, everything works. It's too late for me to switch to another parser so i need to make it work!
Here's what my parser code looks like
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
// factory.setFeature(XmlPullParser.FEATURE_PROCESS_DOCDECL, true);
XmlPullParser xpp = factory.newPullParser();
// get a reference to the file.
File file = new File(Environment.getExternalStorageDirectory() + "/"
+ Constants.SD_CARD_DIR + "/" + Constants.XMLPATH);
// create an input stream to be read by the stream reader.
FileInputStream fis = new FileInputStream(file);
// set the input for the parser using an InputStreamReader
xpp.setInput(new InputStreamReader(fis));
int eventType = xpp.getEventType();
// /
while (eventType != XmlPullParser.END_DOCUMENT) {...}
回答1:
It seems that your xml file starts with the UTF-8 byte-order-mark (see here). Probably happened when you copied the declaration. The solution depends on the editor you're using, some of them can be set not to write the BOM. Sometimes it disappears when you delete the first character of the file and type it again.
回答2:
I just had the same problem and it's actually caused by utf-8 bom encoding,but i could't solve it because the xml file was created by the server,i could't modify it
回答3:
I also had the same problem but I figured out that it is not a fault of not well formed XML document ,Sometimes it would be that problem but this time, it is due by not using correct output stream that the server is using to send the data to the client side ... my server-side code is this :
DataOutputStream dos = new DataOutputStream((OutputStream) response.getOutputStream());
but my client side code is :
InputStream is =(InputStream) httpConnection.openDataInputStream();
so finally I changed the streams to match each other ,then the problem also solved ... I still don't understand why is it happens when those streams are different even the streams are inherited by the same InputStream
(I used this for J2ME sdk 3.0.5)
来源:https://stackoverflow.com/questions/4938231/xml-pull-parser-error-when-declaration-present