2012-07-06 95 views
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) 

回答

3

你不能投一個節點列表中的節點。獲取列表中的第一個元素,如果這是你想要的

NodeList nl = docEle.getElementsByTagName("item"); 
... 
((Node) nl).getNodeValue() <-- this 

如果你真的想要的是,無論是瀏覽清單或獲取列表的元素:

for(Node n : nl) 
    System.out.println(n.getNodeValue()); 

編輯

我的錯誤,這不是itterable,試圖通過規模做到這一點:

for(int i=0; i < nl.getLength(); i++) 
{ 
    Node childNode = nl.item(i); 
    System.out.println(childnode.getNodeValue()); 
} 

但是,我懷疑這還不是你想要做的,因爲你得到的是元素,元素沒有值,它們有文本節點有值。這意味着你需要子節點(文本節點)。所以你可能想要類似

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()); 
} 
+0

我也會說異常報告的第一行清楚地告訴你這一點。 – Woody 2012-07-06 11:07:02

+0

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

+0

做到了像你說的,但在那裏說:\t \t爲(節點n:NL){ 它強調NL和它說只能遍歷數組或java.lang.Iterable – Pita 2012-07-06 11:11:35