How to get a node value with XmlPullParser
Asked Answered
O

3

5

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!

Osmo answered 28/9, 2011 at 8:39 Comment(1)
I had the opposit problem, couldn't get name and value ;) figured it out though getAttributeValue() was what I searched for.Audry
R
5

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.

Roue answered 28/9, 2011 at 8:58 Comment(1)
Im embarrased, that was actually all I needed. Thanks!Osmo
O
12

nextText() method will do the trick

Oxblood answered 1/11, 2011 at 20:10 Comment(1)
this is the actual answer..!!Vito
R
5

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.

Roue answered 28/9, 2011 at 8:58 Comment(1)
Im embarrased, that was actually all I needed. Thanks!Osmo
B
1

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.

Bine answered 18/10, 2017 at 11:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.