简体   繁体   English

如何在Android上解析XML

[英]how to parse XML on android

I am using this code to parse xml file with Java but It doesn't work with android SDK 我正在使用此代码使用Java解析xml文件,但不适用于android SDK

   try {
        URL url = new URL("http://example.com/file.xml");
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(url.openStream());

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

        for (int i = 1; i < nodeList.getLength(); i++) {
            Element element = (Element)nodeList.item(i);
            System.out.println(element.getFirstChild().getNodeValue());
        }

    } catch (ParserConfigurationException parserConfigurationException) {
    } catch (SAXException sAXException) {
    } catch (IOException iOException) {
    }

when i try to put the value in String the value always = null !! 当我尝试将值放入String时, value always = null what is wrong ??? 怎么了 ???

PS : the app has Internet permission PS:该应用程序具有互联网许可

you can parse XML using some thing like that : 您可以使用类似以下内容来解析XML:

  1. Getting XML content by making HTTP request 通过发出HTTP请求来获取XML内容
  2. Parsing XML content and getting DOM element of xml. 解析XML内容并获取xml的DOM元素。
  3. Get each xml child element value by passing element node name. 通过传递元素节点名称来获取每个xml子元素值。

Depending up on the XML format, Some times we may also need to use getTextContent() or getAttribute() . 取决于XML格式,有时我们可能还需要使用getTextContent()getAttribute() Can you please try using getTextContent instead of getNodeValue once. getNodeValue一次尝试使用getTextContent而不是getNodeValue

One more best option is to debug. 另一个最佳选择是调试。 Keep some debug point and check what are the childs and what is the information that the Node contains. 保留一些调试点,并检查哪些子项以及节点包含的信息是什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM