Android的XmlPullParser - 如何解析这个XML示例文件? [英] Android XmlPullParser - how to parse this XML sample file?

查看:140
本文介绍了Android的XmlPullParser - 如何解析这个XML示例文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有简单的XML文件。

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>

如何获得子标签,其中父ID = 2的值?这里是我的code。

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?

    }
}

我要TODO标签之后做什么?我试着做,而 - 一切都错了。
编辑:似乎XmlPullParser不能在这种情况下被使用。它不能看到具有不同属性的相等的标记之间的差异。我会尝试使用的SAXParser的的startElement(URI字符串,字符串的localName,字符串QNAME,属性的属性)。

What should I do after TODO label? I tried do-while - everything was wrong. 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.

推荐答案

与布尔标志做到了这一点。当你找到的元素,你需要=>设置标志为true,并继续解析。当发现关闭该元素的标签=>设置的标志为false。

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;
}

输出:
3
4

OUTPUT: 3 4

这篇关于Android的XmlPullParser - 如何解析这个XML示例文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆