问题
I've got simple XML file.
<Parent id=1>
<Child>1</Child>
<Child>2</Child>
</Parent>
<Parent id=2>
<Child>3</Child>
<Child>4</Child>
</Parent>
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 = xpp.next()) != 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.
回答1:
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(flag)
{
if (event == XmlPullParser.START_TAG && xpp.getName().equalsIgnoreCase("Child"))
System.out.println(xpp.getText());
}
}
}
if (event == XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("Level"))
{
flag = false;
}
OUTPUT: 3 4
来源:https://stackoverflow.com/questions/15187607/android-xmlpullparser-how-to-parse-this-xml-sample-file