0

I try to read a XML file created by my app using this code:

XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new StringReader(data));
int eventType = xpp.getEventType();

while(eventType != XmlPullParser.END_DOCUMENT)
{
    switch(eventType)
    {
        case XmlPullParser.START_TAG:
        {
            String tagName = xpp.getName();
            // do something
            break;
        }
        case XmlPullParser.TEXT:
        {
            // get text...
            break;
        }
        case XmlPullParser.END_TAG:
        {
            // do something
            break;
        }
    }

    eventType = xpp.next();
}

but at first, when eventType is START_DOCUMENT, next() function throws exception: org.xmlpull.v1.XmlPullParserException: name expected (position:START_TAG @2:2 in java.io.StringReader@41084cc8)

Do you have any idea why?

Here is my XML file:

<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
<0>
  <createTime>1419453655800</createTime>
  <editTime>1419453655800</editTime>
  <color>2</color>
  <text>ooooo</text>
</0>
<1>
  <createTime>1419453586197</createTime>
  <editTime>1419453605679</editTime>
  <color>1</color>
  <text>uuuuuuuuu</text>
</1>
<2>
  <createTime>1419453358866</createTime>
  <editTime>1419453597124</editTime>
  <color>2</color>
  <text>yyyyyyyyyy</text>
</2>
kjhughes
  • 106,133
  • 27
  • 181
  • 240
Mustafa Chelik
  • 2,113
  • 2
  • 17
  • 29

1 Answers1

1

Make your XML well-formed by giving it a single root element and making element names start with letters, not numbers:

<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
<top>
  <e0>
    <createTime>1419453655800</createTime>
    <editTime>1419453655800</editTime>
    <color>2</color>
    <text>ooooo</text>
  </e0>
  <e1>
    <createTime>1419453586197</createTime>
    <editTime>1419453605679</editTime>
    <color>1</color>
    <text>uuuuuuuuu</text>
  </e1>
  <e2>
    <createTime>1419453358866</createTime>
    <editTime>1419453597124</editTime>
    <color>2</color>
    <text>yyyyyyyyyy</text>
  </e2>
</top>
Community
  • 1
  • 1
kjhughes
  • 106,133
  • 27
  • 181
  • 240
  • You were right. It worked after inserting text before numbers. But I have a question: when I call getName function, I get end-line and space characters as well. Is it normal? – Mustafa Chelik Jan 06 '15 at 22:43
  • 1
    No, that's not normal. For START_TAG, END_TAG, and ENTITY_REF events, `getName()` should return Strings, which should never have spaces or newlines; for other events, `getName(`) should return null. I'd post a new question with a [**Minimal, Complete, and Verifiable Example (MCVE)**](http://stackoverflow.com/help/mcve) that specifically shows `getName()` returning EOL and spaces. – kjhughes Jan 07 '15 at 02:30
  • You are right. When a tag doesn't have text (like or ) getText() returns "\n ". Sorry but I didn't get your last sentence. Thank you – Mustafa Chelik Jan 07 '15 at 20:22