Search code examples
androidandroid-xmlpullparser

Xmpullparser Android nested tag


I have problem with parsing my xml document, I need take values from section: coordinates. There is not problem with parsing and section.

Below there is my xml document and part of code. Any sugestions?

<?xml version="1.0" encoding="utf-8"?>
<kml xmlns="http://earth.google.com/kml/2.1">
<Document>
        <Placemark id="placemark1">
            <name>test_name</name>
            <description>geom_test</description>
            <point>
                <coordinates>40.751816, -73.959119</coordinates>
            </point>
        </Placemark>
        <Placemark id="placemark2">
            <name>test_name1</name>
            <description>geom_test</description>
            <point>
                <coordinates>40.751816, -73.959119</coordinates>
            </point>
    </Placemark>
</Document>
</kml>

Code:

while (parser.next() != XmlPullParser.END_TAG) {
    if (parser.getEventType() != XmlPullParser.START_TAG) {
        continue;
    }
    String name = parser.getName();
    if (name.equals("Placemark")) {
        String id = null, date = null, pob = null;
        while (parser.next() != XmlPullParser.END_TAG) {
            if (parser.getEventType() != XmlPullParser.START_TAG) {
                    continue;
            }
            name = parser.getName();
            if (name.equals("name")) {
                id = readText(parser);
            } else if (name.equals("description")) {
                date = readText(parser);
            } else if (name.equals("point")) {
                parser.nextTag();
            } else if (name.equals("coordinates")) {
                pob = readText(parser);
            }
        }
        myDbHelper.insertData(id, date, pob);

Solution

  • Your problem is that nextTag() goes to coordinates tag directly and the next() call gives you a end tag.

    So, you should get the text after call nextTag or directly call next and reenter in the while loop (with next you are "opening" coordinates tag and not "inside").

    Option1 nextTag for next:

    } else if (name.equals("point")) {
        parser.next();
    }
    

    Option 2 is to call getText after getNextTag:

    } else if (name.equals("point")) {
        parser.nextTag();
        if (parser.getName().equals("coordinates")) {
            pob = parser.nextText();
        }
    }