Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing XML from website to an Android device

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?

like image 581
carsey88 Avatar asked Dec 16 '22 05:12

carsey88


1 Answers

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".

like image 149
Mxyk Avatar answered Jan 05 '23 04:01

Mxyk