1

I'm using XmlPullParser to parse some custom XML. I open the XML file like this...

XmlPullParser xpp = activity.getResources().getXml(R.xml.myXML);

And later I read the following XML node

<L>  ####</L>

using the code

String str = "";
if( xpp.next() == XmlPullParser.TEXT )
    str = xpp.getText();
return str;

Instead of returning

'  ####'

I get

' ####'

(single quotes added by me for clarity.) NOTE The missing leading space.

It appears getText is stripping the leading space? When the XML doesn't contain a leading space, my code works as expected.

I can't find any property of XMLPullParser that allows me to tell it to keep all whitespace. Nor can I change the XML to add double quotes around the text with leading whitespace.

David Welch
  • 369
  • 1
  • 9
  • As far as I know, it will do this because in XML, double-spaces are treated as one space (not just leading). I don't believe `XmlPullParser` has a way around this. – Cat Aug 17 '12 at 19:41
  • Did you read [this](http://developer.android.com/reference/org/xmlpull/v1/XmlPullParser.html#TEXT) ? – gontard Aug 17 '12 at 20:18
  • Eric - Only when the double space is leading, is one of the spaces dropped. If the double space is in the middle of the string, it is preserved. – David Welch Aug 20 '12 at 03:02
  • gontard - Yep, read your link. Tried a few other things but none of them changed anything. – David Welch Aug 20 '12 at 03:02
  • Are you trying to parse Sokoban levels? :) I faced the same issue and found possible solutions [here](http://stackoverflow.com/q/1587056/506695). [Quoting the text](http://stackoverflow.com/a/5342985/506695) is most acceptable in my case due to it doesn't break level in monospace text editor leaving spaces as is. As an alternative you always can use an original Java to parse XMLs. – ezze Sep 11 '13 at 15:41

1 Answers1

1

XmlPullParser.next() and XmlPullParser.getText() can return the content in several pieces, in an unpredictable way. In your case, maybe the very first space char is returned as a first piece and silently dropped by your program if it iterates on xpp.next() without concatenating the pieces. The algorithm should more be:

String str = "";
while (xpp.next() == XmlPullParser.TEXT) {
    str += xpp.getText();
}
return str;
philippe_b
  • 38,730
  • 7
  • 57
  • 59
  • Your suggestion sounded promising, but didn't change anything. I enter the while loop, and then the next xpp.next() call exits. I even tried the following with no change... `String str = ""; while(true) { int r = xpp.nextToken(); if( r != XmlPullParser.TEXT && r != XmlPullParser.IGNORABLE_WHITESPACE ) break; str += xpp.getText(); } return str; ` – David Welch Aug 20 '12 at 03:05