Java – Android XmlPullParser – how to parse this XML sample file


I've got simple XML file.

<Parent id=1>
<Parent id=2>

How to get values of Child tags where Parent id=2? Here's my code.

XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new StringReader(readFileAsString(xmlFilename)));

int event;
while ((event = != XmlPullParser.END_DOCUMENT)
//found <Parent id=2> 
    if (event == XmlPullParser.START_TAG && xpp.getName().equalsIgnoreCase("Parent")
            && Integer.parseInt(xpp.getAttributeValue(null, "id")) == 2)

        //TODO - what's next?


What should I do after TODO label? I tried do-while – everything was wrong.
EDIT: Seems that XmlPullParser can't be used in this case. It can't see the difference between equal tags with different attributes. I'll try to use startElement(String uri, String localName, String qName, Attributes attributes) of SAXParser.

Best Solution

Achieved this with boolean flags. When you found element you need => set flag to true and continue parsing. When found closing tag of that element => set flag to false.

    if (event == XmlPullParser.START_TAG && xpp.getName().equalsIgnoreCase("Child"))
if (event == XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("Level"))
    flag = false;