aspose file tools
The moose likes Beginning Java and the fly likes Type Casting Question with DOM Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Type Casting Question with DOM" Watch "Type Casting Question with DOM" New topic
Author

Type Casting Question with DOM

Mike Mann
Greenhorn

Joined: Nov 21, 2003
Posts: 4
I was working with some code I found in a book (Parsing with DOM) and I ran into the following:


The question I have is why does Element need to be casted? Wouldn't

give you a Element Object?
If not, could you explain why.
Thanks for any Answers
[ December 24, 2004: Message edited by: Mike Mann ]
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Did you try it? The compiler message can be pretty informative sometimes. (And absolutely useless sometimes, too.) Anyhow, this would probably say something about not being able to turn a Node into an Element without an explicit cast.

If you look at your first line your itemlist variable is of type NodeList. And if you look at the doc for NodeList it only knows how to work with instances of Node. In fact it can hold instances of any object of type Node or any subinterface. Because Element extends Node, we say an "Element is a Node" so NodeList can hold objects of type Element with no problem.

If you get an object out of the list and it really is an Element you can cast it to Element. How do you know the Nodes in the NodeList are really Elements? Go back to the Document javadoc and see getElementsByTagName returns a "NodeList of all the Elements ...".

This is kinda slick. You can put an object instance of a class into a variable declared with any superclass or super interface. Document puts Element objects into a NodeList and you get them back out. Because you know what they are you feel safe casting them back to Element. But the compiler doesn't understand or trust that there are Elements in there. It makes you tell it with an explicit cast.

Hope that helps!!


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Mike Mann
Greenhorn

Joined: Nov 21, 2003
Posts: 4
Thanks Stan that helped me a lot! I appreciate that people are willing to spend time to help others.
[ December 24, 2004: Message edited by: Mike Mann ]
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
That's why we're here. It's a joy when it works!
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Type Casting Question with DOM
 
Similar Threads
getting new line as first child
dtd clarification
Java XML DOM Parsing
How do I use DOM to gather information on an XML file with repeating child elements?
How to get nested elements using DOM