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 ]
Joined: Jan 29, 2003
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
Joined: Nov 21, 2003
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 ]