0
我想通過XML文件填充下拉列表。 我已經創建了XML文件,並且我已經編寫了第一個讀取xml文件的代碼,並且只給我從xml文件中編譯的項目,但是當我想稍後運行代碼時給了我錯誤。使用Java代碼的XML解析器
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;
}
錯誤消息:
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)
我也會說異常報告的第一行清楚地告訴你這一點。 – Woody 2012-07-06 11:07:02
public ArrayList readXML(){ \t \t \t \t DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); \t \t DocumentBuilder db; \t \t \t嘗試{ \t \t 分貝= dbf.newDocumentBuilder(); \t \t \t \t \t Document dom; \t \t \t dom = db.parse(「PVS_XML.xml」); \t \t元素docEle = dom.getDocumentElement(); \t \t \t \t NodeList nl = docEle.getElementsByTagName(「item」); \t \t((Node)nl).getNodeValue(); \t \t \t 爲\t(節點n:NL){ \t \t的System.out.println(n.getNodeValue()); \t \t} \t \t \t}趕上(例外五){ \t \t \t \t // TODO自動生成的catch程序塊 \t \t \t \t即的printStackTrace(); \t \t \t} \t \t return null; \t} – Pita 2012-07-06 11:11:00
做到了像你說的,但在那裏說:\t \t爲(節點n:NL){ 它強調NL和它說只能遍歷數組或java.lang.Iterable – Pita 2012-07-06 11:11:35