DecodeGnome
DecodeGnome

Reputation: 1809

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!

Upvotes: 5

Views: 8147

Answers (3)

lucidbrot
lucidbrot

Reputation: 6188

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.

Upvotes: 1

k7k0
k7k0

Reputation: 1031

nextText() method will do the trick

Upvotes: 12

svidnas
svidnas

Reputation: 581

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.

Upvotes: 5

Related Questions