Hell there, I have been stuck on this for a bit now. I know it should be simple but I can’t seem to find where I went wrong. I built my little XML parser after following and trying to adapt the DOM Parser example here: http://www.ibm.com/developerworks/opensource/library/x-android/index.html I have it recognising the nodes but I, for the life of me, can’t figureout why it is telling me the value of the nodes is “null”. Help would be greatly appreciated.
My XML test file.
<?xml version="1.0"?>
<Person>
<Name>Scott</Name>
<Gender>Male</Gender>
<More>And So On..</More>
</Person>
My Parser code is.
public class XMLParser {
InputStream xmlDocument;
TextView tv;
public XMLParser(InputStream xmlDocument, TextView tv) {
this.xmlDocument = xmlDocument;
this.tv = tv;
}
public HashMap<String, String> parse() {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
HashMap<String, String> xmlItems = new HashMap<String, String>();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document dom = builder.parse(xmlDocument);
Element root = dom.getDocumentElement();
NodeList items = root.getElementsByTagName("Person");
Element rootElement = (Element)items.item(0);
items = rootElement.getChildNodes();
tv.append("\nParser, # of Items: " + String.valueOf(items.getLength()));
for (int i = 0; i < items.getLength(); i++){
Node item = items.item(i);
xmlItems.put(item.getNodeName(), item.getNodeValue());
tv.append("\nNM: " + item.getNodeName() + " NV: " + item.getNodeValue());
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return xmlItems;
}
}
I’m using XmlPullFactory, and it’s not so bad.
Edit for Converting to Hashmap
Note that this isn’t really recommended. This code does not check for duplicate keys in the hashmap, and it will overwrite any existing keys!!!