I am starting an Android application that will parse XML from the web. I've created a few Android apps but they've never involved parsing XML and I was wondering if anyone had any tips on the best way to go about it?
Here's an example:
        try {
            URL url = new URL(/*your xml url*/);
            URLConnection conn = url.openConnection();
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(conn.getInputStream());
            NodeList nodes = doc.getElementsByTagName(/*tag from xml file*/);
            for (int i = 0; i < nodes.getLength(); i++) {
                Element element = (Element) nodes.item(i);
                NodeList title = element.getElementsByTagName(/*item within the tag*/);
                Element line = (Element) title.item(0);
                phoneNumberList.add(line.getTextContent());
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
In my example, my XML file looks a little like:
<numbers>
   <phone>
      <string name = "phonenumber1">555-555-5555</string>
   </phone>
   <phone>
      <string name = "phonenumber2">555-555-5555</string>
   </phone>
</numbers>
and I would replace /*tag from xml file*/ with "phone" and /*item within the tag*/ with "string".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With