Roger
Roger

Reputation: 6527

How do I get XML's element content in Android?

say I have an XML node and I need to get content of a certain element, say

    NodeList nodes = doc.getElementsByTagName("msg");

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

        Element e = (Element)nodes.item(i);
        Log.e("XML: " , e.get... WHAT GOES INTO HERE ...("id") );
    }   

and I need the get the content of the "id" element, what's the best way to do it?

Thanks!

Upvotes: 1

Views: 603

Answers (1)

Chris
Chris

Reputation: 23171

If the structure of your XML looks something like this:

<someroot>
    <msg>
       <sometag>hi</sometag>
       <id>Some Text</id>
     </msg>
<someroot>

Then you can do this to access the contents of the id node:

NodeList nodes = doc.getElementsByTagName("msg");
        for (int i = 0; i < nodes.getLength(); i++) {           
            if (nodes.item(i).getNodeType() == Node.ELEMENT_NODE) {
                NodeList msgChildren = nodes.item(i).getChildNodes();
                for (int j = 0; j < msgChildren.getLength(); j++) {
                    if (msgChildren.item(j).getNodeType() == Node.ELEMENT_NODE) {
                        Element e = (Element) msgChildren.item(j);
                        if ("id".equals(e.getNodeName())) {
                            System.out.println(e.getTextContent());
                        }
                    }
                }
            }
        }

Upvotes: 2

Related Questions