Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XmlPullParser get child nodes

I'm working with an OpenStreetMap (.osm) file with Android's XmlPullParser. The part I'm having problems with is this:

  <way id='-13264' action='modify' visible='true'>
    <nd ref='-13252' />
    <nd ref='-13251' />
    <nd ref='-13249' />
  </way>

I need to work with the nd- nodes within every way- node, one way- node at a time (that's the crux), creating a certain data structure between those nodes to be precise. There seems to be no convenient method to get all the child nodes of one node in the XmlPullParser, so i tried a lot of that nested if/elseif- stuff on those nodes, but can't get it to work. Can someone provide me with some sample code to work with child nodes of a node, but keeping the child nodes of similar parent nodes seperate?

like image 650
fweigl Avatar asked Sep 19 '11 15:09

fweigl


2 Answers

This is how I would parse this. You are free to use it, but you will have to come up with the implementation for the Way class on your own! :)

List<Way> allWays = new ArrayList<Way>();
Way way;
int eventType;
while((eventType = parser.getEventType())!=XmlPullParser.END_DOCUMENT){
    if(eventType==XmlPullParser.START_TAG) {
        if("nd".equals(parser.getName()) {
            way.addNd(parser.getAttributeValue(0));
        }
        else if("way".equals(parser.getName()) {
            way = new Way();
        }
    }
    else if(eventType==XmlPullParser.END_TAG) {
        if("way".equals(parser.getName()) {
            allWays.add(way);
        }
    }
    parser.next();
}

Of course if the xml coming to you is even a slight bit different this exact code may not work. Again, I will leave that as an exercise for the asker.

like image 171
nicholas.hauschild Avatar answered Nov 19 '22 18:11

nicholas.hauschild


You can use the following code:

    int eventType=parser.getEventType();
    while(eventType!=XmlPullParser.END_DOCUMENT){
         if(eventType==XmlPullParser.START_TAG 
               && parser.getName().equals("nd"){
              //process your node...
         }
         parser.next();
    }
like image 2
Ovidiu Latcu Avatar answered Nov 19 '22 18:11

Ovidiu Latcu