XmlPullParser名称预期异常

时间:2015-01-06 21:21:26

标签: java android xml exception xmlpullparser

我尝试使用以下代码读取我的应用创建的XML文件:

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();
}

但首先,当 eventType 为START_DOCUMENT时, next()函数会抛出异常: org.xmlpull.v1.XmlPullParserException:name expected(position:START_TAG) @ 2:2 in java.io.StringReader@41084cc8)

你知道为什么吗?

这是我的XML文件:

<?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>

1 个答案:

答案 0 :(得分:1)

通过为其提供单个根元素并使元素名称以字母而不是数字开头来创建XML well-formed

<?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>