-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]
能否請你幫我這個。