Re: Help with XML processing using DOM




kernco wrote:
XML file:
<?xml version="1.0"?>

<a>
<b>
<c>foo</c>
<d>foo</d>
<d>foo</d>
</b>
<e>
</e>
</a>

Relevant code:
Node domNode = doc.getDocumentElement();
System.out.println(domNode.getNodeName());
domNode = domNode.getFirstChild();
System.out.println(domNode.getNodeName());

do {
if (domNode.getNodeName().equals("b")) {
...
} else if ...
...
} while ((domNode = domNode.getNextSibling()) != null);

You will notice my println statements there to help figure out the
problem. The first one prints "a" as expected, I'd then expect the
first child to be "b", but instead it prints "#text". I changed the
second println to print the node value instead of name, and it prints
a single whitespace character. Why isn't this getting the Node at
"b"?

Thanks,
Colin

try Element.getTagName()

When I try to cast the Node to an Element, I get a runtime error:
Exception in thread "main" java.lang.ClassCastException:
com.sun.org.apache.xerces.internal.dom.DeferredTextImpl cannot be cast
to org.w3c.dom.Element


You're not on an Element node you're on a Text node.
As you iterate the children nodes you'll have to check
what type of node you're currently referencing.
See the table at:
<http://java.sun.com/javase/6/docs/api/org/w3c/dom/Node.html>


.