XML属性解析

时间:2013-11-29 10:45:06

标签: android xml xmlpullparser

我正在构建一个我必须解析XML属性的应用程序。我的XML看起来像这样:

<ad type="interstitial" animation="none">
<interstitial preload="0" autoclose="0" type="url" url="http://account.mobfox.com/activation_vad.php" orientation="portrait">       
</interstitial>
</ad>

我尝试使用以下代码:

try {
    XMLParser parser = new XMLParser();
    xml = parser.getXmlFromUrl(URL);

    XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
    XmlPullParser parser1 = factory.newPullParser();
    parser1.setInput(new StringReader(xml));

    while (!"interstitial".equals(parser1.getName())
        && parser1.getEventType() != XmlPullParser.START_TAG) {
        parser1.next();
    }

    Log.d("URL --> ", parser1.getAttributeValue(null, "url"));

} catch (Exception e) {
    e.printStackTrace();
}

但是,我无法从属性中打印URL。 我究竟做错了什么?任何形式的帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

最好能使用xpath概念。它很容易实现。这是Link ...您也可以在线运行查询here ...

答案 1 :(得分:0)

试试这个..

Log.d("URL --> ", ""+parser1.getAttributeValue(null, "url"));

因为你在Log.d null

中传递参数

修改

URL url = new URL("Your URL");
                DocumentBuilderFactory dbf = DocumentBuilderFactory
                        .newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                Document doc = db.parse(new InputSource(url.openStream()));

                doc.getDocumentElement().normalize();

                NodeList nodeList = doc.getElementsByTagName("ad");

                for (int i = 0; i < nodeList.getLength(); i++) {

                    Node node = nodeList.item(i);

                    Element fstElmnt = (Element) node;
                    NodeList nameList = fstElmnt.getElementsByTagName("interstitial");
                    Element nameElement = (Element) nameList.item(0);
                    nameList = nameElement.getChildNodes();                       

                    System.out.println("Value : "
                            + (nameElement.getAttribute("url")));
                }