Question

I am parsing a XML file as follows:

<ROW>
<INDUSTRY_ID>1</INDUSTRY_ID>
<ID>314</ID>
</ROW>

Here's my code:

NodeList titleList = list.getElementsByTagName("ROW");
Log.w("nodeName is ",titleList.item(0).getChildNodes().item(1).getFirstChild().getNodeName());
Log.w("nodeValue is ",titleList.item(0).getChildNodes().item(1).getFirstChild().getNodeName());

I can successfully obtain the content of the tag and tag, namely, I got "1" and "314" resp.; However, I got #text from getNodeName(). I have also tried:

titleList.item(0).getChildNodes().item(1).getFirstChild().getNodeName().toString()

But I was still getting #text. My question is how do I get "INDUSTRY_ID" and "ID" instead?

Was it helpful?

Solution

Your have navigated down to the Text node. Text nodes doesn't technically have names, just (text) values. You want this:

NodeList titleList = list.getElementsByTagName("ROW");
Log.w("nodeName is ",titleList.item(0).getChildNodes().item(1).getNodeName());
Log.w("nodeValue is ",titleList.item(0).getChildNodes().item(3).getNodeName());

However, this is a very non-robust way of accessing element nodes and values, since it depends on white space formatting. Use Xpath to retrieve a list of needed elements and access their respective names and values

XPath xp = XPathFactory.newInstance();
NodeList elements = (NodeList) xp.evaluate(doc, "//ROW/*", XPathConstants.NODESET); 
for(int i=0; i < elements.getLength(); ++i) {
    String name = elements.itemt(i).getNodeName();
    String value = elements.itemt(i).getTextContent();
} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top