2015-11-09 51 views
-2

我有一個XML文件,如下圖所示:如何解析XML文件並在Java中檢查每個元素是否有子元素?

<customers> 
    <customer> 
     <name>XXX</name> 
     <address>Nagar</address> 
     <number> 
      <num1>123</num1> 
      <num2>456</num2> 
     </number> 
    </customer> 
    <customer> 
     <name>YYY</name> 
     <address>Nagar</address> 
     <number> 
      <num1>789</num1> 
      <num2>012</num2> 
     </number> 
    </customer> 
</customers> 

我需要解析從上到下整個XML,並得到每個元素的子節點的信息。

例外輸出:(節點=孩子)

customers = customer,customer 
customer = name,address,number 
name = null 
address = null 
number = num1,num2 
num1 = null 
num2 = null 
customer = name,address,number 
name = null 
address = null 
number = num1,num2 
num1 = null 
num2 = null 

我用DOM此。下面給出的代碼:

NodeList nodeList = doc.getElementsByTagName("*"); 
for (int i = 0; i < nodeList.getLength(); i++) { 
Node node = nodeList.item(i); 
    if (node.getNodeType() == Node.ELEMENT_NODE) { 
     System.out.println(node.getNodeName()+" = "+node.getChildNodes()); 
    } 
} 

但我得到的輸出是這樣的:

customers = [customers: null] 
customer = [customer: null] 
name = [name: null] 
address = [address: null] 
number = [number: null] 
num1 = [num1: null] 
num2 = [num2: null] 
customer = [customer: null] 
name = [name: null] 
address = [address: null] 
number = [number: null] 
num1 = [num1: null] 
num2 = [num2: null] 

能否請你幫我這個。

回答

1

您需要另一個循環在循環,通過孩子

這工作遍歷:

NodeList nodeList = document.getElementsByTagName("*"); 
for (int i = 0; i < nodeList.getLength(); i++) 
    { 
    Node node = nodeList.item(i); 
    if (node.getNodeType() == Node.ELEMENT_NODE) 
     { 
     Element element=(Element) node; 

     System.out.print(element.getNodeName()+" = "); 
     boolean is_first_child=true; 

     // CHILDS 
     NodeList nodechilds=node.getChildNodes(); 

     for (int j = 0; j < nodechilds.getLength(); j++) 
      { 
      Node a_child = nodechilds.item(j); 

      if (a_child.getNodeType() == Node.ELEMENT_NODE) 
       { 
       if (!is_first_child) System.out.print (","); 
       System.out.print (a_child.getNodeName()); 

       is_first_child=false; 
       } 
      } 

    if (is_first_child) System.out.print ("null"); 
    System.out.println(); 
    } 
}