2 xiaoyan 12 xiaoyan_12 于 2013.03.11 10:16 提问

通过 XMLPull 解析器如何获得属性使用?

我贴出xml文件的一部分代码,显示我想获得的内容

<media:content medium="image" url="http://msnbcmedia.msn.com/j/MSNBC/Components/Photo/_new/111010-romney-health-4p.thumb.jpg">
                <media:credit role="provider">Getty Images file</media:credit>
                <media:copyright>2010 Getty Images</media:copyright>
                <media:text><![CDATA[<p><a href="http://www.msnbc.msn.com/id/44854320/ns/politics-decision_2012/"><img align="left" border="0" src="http://msnbcmedia.msn.com/j/MSNBC/Components/Photo/_new/111010-romney-health-4p.thumb.jpg" alt="Mitt Romney speaks at the National Press Club March 5, 2010 in Washington, D.C." style="margin:0 5px 5px 0" /></a></p><br clear="all" />]]></media:text>
            </media:content>

现在我想检索 URL tab,如何检索呢?
用的下面的代码:

if(parser.getName().equalsIgnoreCase("media:content"))
{
    Log.d("media count-->",parser.getAttributeCount()+"");
}      

然后给出的是-1.
请求大家给点意见,如何得到图像的url?

1个回答

zxd_72
zxd_72   2013.03.11 11:35
已采纳

在if语句中调用 getAttributeValue

parser.getAttributeValue(null, "url") 

当 media:content 的解析器设置为END_TAG 部分,现在的if 语句也可能是 true,所以确保 getEventType()和 START_TAG 相同。

public void parseXml() throws XmlPullParserException, IOException
{
    XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
    XmlPullParser parser = factory.newPullParser();
    parser.setInput(new StringReader(
            "<media:content medium=\"image\" url=\"http://msnbcmedia.msn.com/j/MSNBC/Components/Photo/_new/111010-romney-health-4p.thumb.jpg\">"
                    + "<media:credit role=\"provider\">Getty Images file</media:credit>"
                    + "<media:copyright>2010 Getty Images</media:copyright>"
                    + "<media:text><![CDATA[<p><a href=\"http://www.msnbc.msn.com/id/44854320/ns/politics-decision_2012/\"><img align=\"left\" border=\"0\" src=\"http://msnbcmedia.msn.com/j/MSNBC/Components/Photo/_new/111010-romney-health-4p.thumb.jpg\" alt=\"Mitt Romney speaks at the National Press Club March 5, 2010 in Washington, D.C.\" style=\"margin:0 5px 5px 0\" /></a></p><br clear=\"all\" />]]></media:text>"
                    + "</media:content>"));

    while (!"media:content".equals(parser.getName()) && parser.getEventType() != XmlPullParser.START_TAG) {
        parser.next();
    }
    Log.d("media count -->", parser.getAttributeValue(null, "url"));
}
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!