The other day I had an small issue trying to show the data contained into a DOM element, due that I was targeting a null value, because of the way that Node and Element are managed.
Let’s go to the beginning. What I had was a hole Document store in a variable, from that document I got a NodeList of Elements (in this case as it is a NodeList they are Node) that have this aspect, a normal element with data inside:
<c:customer xmlns:c=”http://engage.bt.com/customer”>
<c:id>1</c:id>
<c:name>John</c:name>
<c:lastname>Smith</c:lastname>
<c:department>Finance</c:department>
</c:customer>
I wanted to take the values that the child within this Node have, but they way that the type Node is manages doesn’t allow you to get the children of this element and get the node value that is inside a child such as <c:id>, for instance, because you end up getting the null point that I commented as my problem.
So here it comes the trick, what you have to do is cast the Node (the one shown above) into an Element.
Element customerElement = (Element)customersList.item(i);
Once you have this done, you have to get the Elements within the father by using the function getElementsByTagName(String tagName) , where you will get again a NodeList of elements with the tag name that you say. So now we only have this: <c:id>1</c:id>. So now as a list that it is we should point in the first item, so item(0). Once in this item the value is treated as a child so we need to get that child out by using the function getFirstChild(). Now we reach the point where the value is within our node, so we only need to getNodeValue(), which return a String, so we have to be careful and parse the real Type that we need.
Ok this is been specify step by step, but to make it clear what I used in the end is a function in which you give an Element (<c:customer> in this case) and a tagName (any tag of the children) and gives you the value back. The function is not other than this:
private String getData(Element customer, String tagName){
return customer.getElementsByTagName(tagName).item(0).getFirstChild().getNodeValue();
}
Therefore using this call you get the value for free
String customerData = getData(customer,”c:name”);
