Question

I have the following xml file:

<?xml version="1.0" encoding="UTF-8"?>  
<c1>
 <c2 id="0001" n="CM" urlget="/at/CsM" urle="/E/login.jsp">
 </c2>
 <c2 id="0002" n="C2M" urlget="/a2t/CsM" urle="/E2/login.jsp">
 </c2>
</c1> 

I'm trying to load c2's attributes this way:

Document d =
 DocumentBuilderFactory.newInstance()
 .newDocumentBuilder()
 .parse("epxy.xml");
Element  c1 = d.getDocumentElement();
Element c2 = (Element)c1.getFirstChild();
while (c2 != null) {
  ...         
  c2 = (Element)c2.getNextSibling();
}

But I get the exception java.lang.ClassCastException: org.apache.xerces.dom.DeferredTextImpl incompatible with org.w3c.dom.Element in the line

Element c2 = (Element)c1.getFirstChild();

before the loop.

Any hints ? Thanks.

Was it helpful?

Solution

The first child is the whitespace between the end of c1 and the start of c2.

Using w3c DOM to walk the tree is not so easy. If you don't have to use w3c, I recommend dom4j - it is much nicer to use. For example, it will filter text nodes from elements, so you can call

List children = c1.elements();

or, to restrict by name

List children = c1.elements("c2");

OTHER TIPS

The first child of c1 is a text node containing the newline. You need to iterate the children skipping text nodes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top