2017-05-21 140 views
0

我有一個簡單的XMLJAVA XML子解析

 <task id ="MyMethod"> 
      <taskParameter>"Redicted"</taskParameter> 
      <taskParameter>"ServerInitiated"</taskParameter> 
     </task> 
     <task id ="NoRedictedMethod"> 
      <taskParameter>"NoRedicted"</taskParameter> 
     </task> 

,我想用Java來解析它,我試圖用正確的嵌套

 NodeList ParentList = doc.getElementsByTagName("task"); 
     for (int i = 0; i < ParentList.getLength(); i++) { 
      System.out.println("Parent is "+ ParentList.item(i).getTextContent()); 

      NodeList childList = ParentList.item(i).getChildNodes(); 

      for (int j = 0; j < childList.getLength(); j++) { 
       System.out.println("Clild is "+ childList.item(j).getTextContent()); 
      } 
     } 

我的結果是不正確的打印。我究竟做錯了什麼?

PS。我想打印這樣的東西

Parent is MyMethod 
    Clild is Redicted 
    Clild is ServerInitiated 
    Parent is NoRedictedMethod 
    Clild is NoRedicted 
+0

什麼是你想打印?你想要的輸出應該如何? – ayip

+0

我編輯了我的問題來回答你的注意事項 –

回答

1

你打電話給父母是一個屬性節點。因此,要檢索改變你的代碼:

編輯,以避免空格字符在解析

NodeList ParentList = doc.getElementsByTagName("task"); 
     for (int i = 0; i < ParentList.getLength(); i++) { 
      NamedNodeMap attributes = ParentList.item(i).getAttributes(); 

      for (int index = 0; index < attributes.getLength(); index++) { 
       Node attribute = attributes.item(index); 
       System.out.println("Parent is "+ attribute.getNodeValue()); 
      } 

      NodeList childList = ParentList.item(i).getChildNodes(); 

      for (int j = 0; j < childList.getLength(); j++) { 
       String text = childList.item(j).getTextContent(); 
       if (text.trim().length() != 0) { 
       System.out.println("Clild is "+ text); 
       } 
      } 
     } 
+0

我發現我的問題。當它解析XML時,它也會解析這些空白,所以我對第一個節點感到憤怒:「\ n \ t \ t \ t」,「Redicted」,「\ n \ t \ t \ t \ t」「ServerInitiated」, 「\ n \ t \ t \ t \ t」,這就是爲什麼當我將它們打印出來的時候,它們被搞砸了。在這種情況下做什麼? –

+0

非常感謝!我也嘗試過濾空格,如:(!)childList.item(j).getTextContent()。matches(「^ \ n。*」)) 這也適用,但您的解決方案更優雅和通用。 –

+0

我再次表示感謝 –