Android XmlPullParser - how to parse this XML sample file?

笑着哭i 提交于 2019-12-24 08:25:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!