XmlPullParser XML on Android

2019-05-27 08:16发布

I'm trying to parse some XML from Android. Below is a bit of an example of the 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>   

And so on....

This is the actual code:

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   

... And so on

This gives no results, and eventType is always 0 in debugger. The example URL works fine in a browser. Any ideas?

1条回答
萌系小妹纸
2楼-- · 2019-05-27 08:53

You only execute xpp.next() when eventType == XmlPullParser.START_TAG. Move xpp.next it one line down so it always executes.

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  
查看更多
登录 后发表回答