Results 1 to 2 of 2
Like Tree1Likes
  • 1 Post By kjkrum

Thread: Problem casting from org.w3c.dom.Node to my subclass of Node

  1. #1
    msphelix is offline Member
    Join Date
    Aug 2012
    Rep Power

    Default 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.
    And after
    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()
    return whatIwantreturned;
    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: mentImpl cannot be cast to fabproductions.BookXMLElement
    at fabproductions.BooksXMLNodesPanel.fillTitlesCombo(
    Any help will be greatly appreciated.

  2. #2
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Tucson, AZ
    Rep Power

    Default 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.
    Tolls likes this.
    Get in the habit of using standard Java naming conventions!

Similar Threads

  1. Replies: 1
    Last Post: 04-16-2012, 03:29 PM
  2. Value of the node does not get updated!
    By snajalm in forum Advanced Java
    Replies: 1
    Last Post: 10-12-2011, 09:13 AM
  3. node.x
    By java software in forum Java Software
    Replies: 0
    Last Post: 10-10-2011, 08:20 PM
  4. Problem with method updating node I don't want it to...
    By sonofshirt in forum New To Java
    Replies: 6
    Last Post: 09-26-2010, 08:14 PM
  5. XML Node.getNodeValue Problem
    By mindscape777 in forum XML
    Replies: 1
    Last Post: 01-11-2009, 03:22 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts