Problem casting from org.w3c.dom.Node to my subclass of Node
I'm having a problem with the org.w3c.dom Java interfaces used with XML: casting from org.w3c.dom.Node to my subclass of Node.
NodeList nodes = myXMLDocumentNode.getElementsByTagName(“mytagname” );
nodes is a list of all <mytagname> nodes in the XML document represented by myXMLDocumentNode;
public interface org.w3c.dom.Node
public interface org.w3c.dom.Element extends Node
Node node = nodes.item(0);
node is the first <mytagname> node.
Element el = (Element)node;
(or Element el = (Element) nodes.item(0);
el holds the element of the first <mytagname> node and can be used to access the nodes child nodes and their value.
So far so good; but assume I want to extend Node so I can override toString():
public interface BookXMLElement extends Node // compare to public interface Element extends Node
public String toString()
Shouldn't I be able to cast the Node returned by NodeList.item() to BookXMLElement like I can cast it to Element?
BookXMLElement el = (BookXMLElement) nodes.item(0);
This throws a
java.lang.ClassCastException: com.sun.org.apache.xerces.internal.dom.DeferredEle mentImpl cannot be cast to fabproductions.BookXMLElement
at fabproductions.BooksXMLNodesPanel.fillTitlesCombo( BooksXMLNodesPanel.java:438)
Any help will be greatly appreciated.
Re: Problem casting from org.w3c.dom.Node to my subclass of Node
The Node reference returned by NodeList.item() happens to refer to an Element. The cast doesn't make the object it refers to into an Element. If the object the Node reference refers to is not already a BookXMLElement, you can't cast it to that.