XmlPullParser get child nodes
Asked Answered
C

2

7

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?

Capitalist answered 19/9, 2011 at 15:21 Comment(2)
came here looking for the exact same thing, wasn't disappointed. Just an FYI, i just open sourced my util for reading osm.bz2 files from jdk/adk github.com/spyhunter99/osmreaderModification
@Modification Looks good, thanks for sharing!Capitalist
F
8

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.

Furman answered 19/9, 2011 at 15:34 Comment(3)
I'll do it a little different but this gave me the right direction. Thanks!Capitalist
@Ascorbin, I am facing same problem and I am new to the XmlPullParsing please help me. I have posted my question please check this #17808218Bakelite
I am facing same problem #39391767Antiperistalsis
M
2

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();
    }
Maye answered 19/9, 2011 at 15:27 Comment(1)
Please help me with this #39391767Antiperistalsis

© 2022 - 2024 — McMap. All rights reserved.