2012-07-17 68 views
2

我想解析一些来自Android的XML。下面是一个位XML的例子:Android上的XmlPullParser XML

<updates at="1342481821" found="616" sorting="latest_updates" showing="Last 4D"> 
<show> 
    <id> 
     3039 
    </id> 
    <last> 
     -14508 
    </last> 
    <lastepisode> 
     -14508 
    </lastepisode> 
</show> 
<show> 
    <id> 
     30612 
    </id> 
    <last> 
     -13484 
    </last> 
    <lastepisode> 
     163275 
    </lastepisode> 
</show> 

等等....

这是实际的代码:

try { 
    XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); 
    factory.setNamespaceAware(true); 
    XmlPullParser xpp = factory.newPullParser(); 
    URL url = new URL("http://services.tvrage.com/feeds/last_updates.php?hours=" + hours); 
    InputStream stream = url.openStream(); 
    xpp.setInput(stream, null); 
    int eventType = xpp.getEventType(); 

    while (eventType != XmlPullParser.END_DOCUMENT) { 
     if (eventType == XmlPullParser.START_DOCUMENT) { 
     } 
     else if (eventType == XmlPullParser.END_DOCUMENT) { 
     } 
     else if (eventType == XmlPullParser.START_TAG) { 
      if (xpp.getName().equalsIgnoreCase("id")) { 
       showIds.add(Integer.parseInt(xpp.nextText())); 
      } 
      else if (eventType == XmlPullParser.END_TAG) { 
      } 
      else if (eventType == XmlPullParser.TEXT) { 
      } 
      eventType = xpp.next(); 
     } 
    } 
} catch 

...等

这不会产生任何结果,并且调试器中的eventType总是0。示例网址在浏览器中正常工作。有任何想法吗?

+1

哥们试试这个http://xjaphx.wordpress.com/2011/10/16/android-xml-adventure-parsing-xml-data-with-xmlpullparser/ – 2012-07-17 16:07:44

+0

我使用的是混合使它指导和来自Lars Vogel的指导。 http://www.vogella.com/articles/AndroidXML/article.html – Crunch 2012-07-17 16:17:54

回答

3

您只在eventType == XmlPullParser.START_TAG执行xpp.next()。 移动xpp.next它一行下来,所以它总是执行。

while (eventType != XmlPullParser.END_DOCUMENT) { 
     if (eventType == XmlPullParser.START_DOCUMENT) { 
     } 
     else if (eventType == XmlPullParser.END_DOCUMENT) { 
     } 
     else if (eventType == XmlPullParser.START_TAG) { 
      if (xpp.getName().equalsIgnoreCase("id")) { 
       showIds.add(Integer.parseInt(xpp.nextText())); 
      } 
      else if (eventType == XmlPullParser.END_TAG) { 
      } 
      else if (eventType == XmlPullParser.TEXT) { 
      } 
      // eventType = xpp.next(); <-- remove it 
     } 
     eventType = xpp.next(); // <-- move here 
    } 
} catch 
+0

谢谢,这是做的伎俩。 – Crunch 2012-07-17 16:45:21