简体   繁体   中英

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

   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 !! what is wrong ???

PS : the app has Internet permission

you can parse XML using some thing like that :

  1. Getting XML content by making HTTP request
  2. Parsing XML content and getting DOM element of xml.
  3. Get each xml child element value by passing element node name.

Depending up on the XML format, Some times we may also need to use getTextContent() or getAttribute() . Can you please try using getTextContent instead of getNodeValue once.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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