0
<MyEvents>
<Tracking event="first">
<![CDATA[
http://www.myurl.com/test1
]]>
</Tracking>
<Tracking event="second">
<![CDATA[
http://www.myurl.com/test2
]]>
</Tracking>
<Tracking event="third">
<![CDATA[
http://www.myurl.com/test3
]]>
</Tracking>
<Tracking event="fourth">
<![CDATA[
http://www.myurl.com/test4
]]>
</Tracking>
<Tracking event="fifth">
<![CDATA[
http://www.myurl.com/test5
]]>
</Tracking>
</MyEvents>

I have this xml which i need to parse and store. As each node is named the same "Tracking" I dont know how to parse this xml. I want to parse and store urls corresponding with each event names(first, second, third, fourth and fifth in this case) in variables. I am using XMLPullParser and for other parts of this xml parsing was simple by making use of

if(myparser.getName().equalsIgnoreCase("tagname")){
                        //do something
                     }

in case of node with the same name but different event types i dont know how to parse. Any help is appreciated.

3
  • It looks as though you just need to look into handling attributes and filtering by that means through your parser. Commented Jul 10, 2014 at 17:04
  • Take a look at getAttributeValue method. Commented Jul 10, 2014 at 17:15
  • if(parser.getAttributeValue("second",null) != null) { //do something } something like this? Commented Jul 10, 2014 at 17:33

1 Answer 1

1

First, you may declare a inner class like this:

static class Track {
    String event;
    String url;
}

Then, the parsing code:

List<Track> allTracks = new ArrayList<Track>();

myparser.require(XmlPullParser.START_TAG, null, "MyEvents");
while (myparser.next() != XmlPullParser.END_TAG) {
    if (myparser.getEventType() != XmlPullParser.START_TAG) {
        continue;
    }
    String name = myparser.getName();
    if (name.equals("Tracking ")) {
        String event = myparser.getAttributeValue(0); // I'm supposing that there is just one
        myparser.require(XmlPullParser.START_TAG, null, "Tracking ");
        String url = null;
        if (myparser.next() == XmlPullParser.TEXT) {
            url = parser.getText();
            myparser.nextTag();
        }
        Track track = new Track();
        track.event = event;
        track.url = url;
        allTracks.add(track);
    }
}

It's not perfectly but should get a list of tracks, each one with its respective url and event.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a ton for your timely help and the snippet. it helped a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.