Results 1 to 2 of 2
- 08-12-2012, 02:01 AM #1Member
- Join Date
- Aug 2012
- Rep Power
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.
- 08-12-2012, 03:15 AM #2
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.Get in the habit of using standard Java naming conventions!
- By ashu_i20 in forum XMLReplies: 1Last Post: 04-16-2012, 02:29 PM
- By snajalm in forum Advanced JavaReplies: 1Last Post: 10-12-2011, 08:13 AM
- By java software in forum Java SoftwareReplies: 0Last Post: 10-10-2011, 07:20 PM
- By sonofshirt in forum New To JavaReplies: 6Last Post: 09-26-2010, 07:14 PM
- By mindscape777 in forum XMLReplies: 1Last Post: 01-11-2009, 03:22 PM