I am in the proces of creating a helper method that will allow me to traverse an XML document and put each element in a data HashMap and then return it. Here is the method I’ve been working on :
private static HashMap<String, String> traverseNodes( Node n, HashMap<String,String> data )
{
NodeList children = n.getChildNodes();
if( children != null ) {
for( int i = 0; i < children.getLength(); i++ ) {
Node childNode = children.item( i );
String nodeName = childNode.getNodeName();
if(childNode instanceof Element)
{
data.put(nodeName, getStringByTag(nodeName, (Element)childNode));
Log.d("traversal", childNode.getNodeName() + " was saved in hashmap");
}
else
Log.d("traversal", childNode.getNodeName() + " Is not an Element type");
System.out.println( "node name = " + childNode.getNodeName() );
traverseNodes( childNode, data );
}
}
return data;
}
I tried running the example and although I get messages saying that “childNode.getNodeName() + “was saved in hashmap”. but the HashMap returned is empty.
What am I doing wrong?
EDIT! Bonus Question : I edited the code to reflect the changes suggested. It seems, however, that the method itself doesn’t save the values of my XML Document. Are there any problems with the logic in the method ?
You’re creating a new map on each call. You need to pass the existing map into the recursive call. It should probably look like this: