Reputation: 508
I want to populate a Drop Down list via an XML File. I have crated the XML File already and the code i have written firstly to read the xml file and just give me the items from the xml file is compiliing but giving me errors when i want to run the code later.
public ArrayList readXML(){
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db;
try {
db = dbf.newDocumentBuilder();
Document dom;
dom = db.parse("PVS_XML.xml");
Element docEle = dom.getDocumentElement();
NodeList nl = docEle.getElementsByTagName("item");
System.out.println(((Node) nl).getNodeValue());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
Error Message:
java.lang.ClassCastException: com.sun.org.apache.xerces.internal.dom.DeepNodeListImpl cannot be cast to org.w3c.dom.Node
at de.sidion.pvsng.pages.InputPage.readXML(InputPage.java:222)
at de.sidion.pvsng.pages.InputPage.init(InputPage.java:255)
at de.sidion.pvsng.pages.InputPage.<init>(InputPage.java:183)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
Upvotes: 0
Views: 3531
Reputation: 5130
You cant cast a node list to a node. Get the first element of the list if that is what you want
NodeList nl = docEle.getElementsByTagName("item");
...
((Node) nl).getNodeValue() <-- this
if you really want that, either go through the list or get an element of the list:
for(Node n : nl)
System.out.println(n.getNodeValue());
EDIT
My mistake, it is not itterable, try to do it by size:
for(int i=0; i < nl.getLength(); i++)
{
Node childNode = nl.item(i);
System.out.println(childnode.getNodeValue());
}
However, I suspect this is still not what you want to do, as what you are getting are elements, and elements do not have values, they have text nodes that have values. Which means you need the child node (the text node). So you probably want something like
for(int i=0; i<nodeList.getLength(); i++)
{
Element childElement = (Element)nodeList.item(i);
NodeList innernodes = childElement.getChildNodes();
System.out.println(innernodes.item(0).getNodeValue());
}
Upvotes: 3