开发者

How to get a node value with XmlPullParser

Im trying to get values from an XML with the XmlPullParser but can't reach the values I want. The XML-structure is similar to the Android Strings.xml:

<string name="value"> 1 </string>

I 开发者_如何学编程can get "string", "name" & "value" from the XML but can't reach the actual value "1". It seems like the XmlPullParser only works for structures like this:

<value> 1 </value>

Do I need to use another parser or is there a way to reach "1" (the value above) in some way?

Thanks!


nextText() method will do the trick


Have you checked the documentation of the XmlPullParser? It has an example how to use it. Basically you can get the value inside the tags by calling getText when the parser reaches correct position when you're calling next.


To extend the previous answers with a code snippet of how to actually use this.

/* initialization skipped */
eventType = xpp.getEventType();

            while (eventType != XmlPullParser.END_DOCUMENT) {
                if(eventType == XmlPullParser.START_DOCUMENT) {
                    Log.d("Task2/Parser","Start document");
                } else if(eventType == XmlPullParser.START_TAG) {
                    Log.d("Task2/Parser", "Start tag "+xpp.getName());
                    if (xpp.getName().equals("temperature")){
                        temperature = Double.parseDouble(xpp.nextText());
                        return temperature;
                    }
                } else if(eventType == XmlPullParser.END_TAG) {
                    Log.d("Task2/Parser", "End tag "+xpp.getName());
                } else if(eventType == XmlPullParser.TEXT) {
                    Log.d("Task2/Parser", "Text "+xpp.getText());
                }
                eventType = xpp.next();
            }

This code returns the value within the xml tag <temperature> as a double. Obviously, it would need more error handling, but just so other people ending up here can get it with less googling.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜