2017-05-21 3 views
0

Ich habe eine einfache XMLJAVA XML Kind Parsing

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

und ich möchte es mit Java analysieren und ich versuche, sie mit der richtigen Verschachtelung

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

meine Ergebnisse sind nicht direkt zu drucken. Was mache ich falsch?

PS. Ich möchte wie die

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

Was Sie versuchen, drucken? Wie soll Ihre gewünschte Ausgabe aussehen? – ayip

+0

Ich habe meine Frage bearbeitet, um Sie zu beantworten Note –

Antwort

1

etwas drucken, was Sie als Eltern fordern ein Attributknoten ist. So abzurufen, ändert Ihren Code:

Edited Leerzeichen zu vermeiden, während Parsen

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

Ich habe mein Problem gefunden. Wenn es das XML analysierte, analysierte es auch die blancks, also habe ich chilldren für den ersten Knoten: "\ n \ t \ t \ t", "Redicted", "\ n \ t \ t \ t \ t" "ServerInitiated", "\ n \ t \ t \ t \ t" und deshalb, wenn ich sie drucke, sind sie durcheinander. Was ist in diesem Fall zu tun? –

+0

Vielen Dank! Ich habe auch versucht, Leerzeichen mit regulärem Ausdruck zu filtern wie: wenn (! ChildList.item (j) .getTextContent(). Übereinstimmt ("^ \ n. *")) was auch funktioniert, aber Ihre Lösung ist viel eleganter und generischer . –

+0

Ich habe wieder danke –