sandalone
sandalone

Reputation: 41759

XmlPullParser:PI must not start with xml, but only on Android 2.3.3 downwards

I get no error on Android 3.0+, but only on Android 2.2, 2.3.3 when I try to parse a small XML file via XmlPullParser, the app breaks with an error:

org.xmlpull.v1.XmlPullParserException: PI must not start with xml 
(position:unknown @1:5 in java.io.InputStreamReader@40568770) 

What is PI mentioned in the error???

I found out that this may cause the first line of XML file (<?xml version="1.0" encoding="utf-8"?>), but I did not find the reason why this is happening on lower Android versions.

If this is the cause of error (first line of XML file), how can I fix this?

Should I:
a) ask the admin of web server to change XML? If yes, what he should change in XML?
b) substring InputStream using BufferedReader?

Somehow I think that the 2nd approach will cause extra delays on weak Android phones.

EDIT

I pulled XML content from debugger and saw that the first like is ending with \r\n, then the next characters starts. Does this say anything to you?

And this is how XML file look like. It's a small one and there is no visual reason why app is crashing.

<?xml version="1.0" encoding="utf-8"?>
<song>
  <artist>Pink Floyd</artist>
  <title>Shine On You Crazy Diamond</title>
  <picture>http://www.xxyz.com/images/image.jpg</picture>
  <time>Fri, 23 Nov 2012 11:22:31 GMT</time>
</song>

This is how InputStream taken from this XML look like (starting chars only).

Please advise!!!

Upvotes: 6

Views: 3317

Answers (3)

slowcar
slowcar

Reputation: 354

After checking the xml parser source it seems that the issue occurs due to a byte order marker on the beginning of the response, in my case '77u/' (in base64). If you don't convert the stream to String but parse it directly the parser correctly throws this away.

For example instead of

String xml = new String(xmlData, "UTF-8");
KXmlParser parser = new KXmlParser();
parser.setInput(new StringReader(xml));

use

KXmlParser parser = new KXmlParser();
parser.setInput(new ByteArrayInputStream(xmlData), null);

As an alternative you could also substring until the first '<'

Upvotes: 1

hmartinezd
hmartinezd

Reputation: 1196

I was having the same problem with a data file I have been using on an App. Was having this exception on android 2.3.* and the problem was the UTF-8 BOM, so the easier solution I found, on Windows, was use the Notepad++ tool, and that let you convert the file encoding to UTF-8 without BOM and that's it.

Upvotes: 1

yjzhang
yjzhang

Reputation: 5329

Encountered the same problem.

For me I replaced all '\n' with space ' ' and then it worked.

PS:

@Ahmad said, a blank line before could also cause this problem, better to check the first character '<' of a xml string.

Upvotes: 0

Related Questions