我的XML看起來像這 -getChildNodes給人意想不到的結果
<collected_objects>
<object flag="complete" id="objId" version="1">
<variable_value variable_id="varId">ValueGoesHere</variable_value>
<reference item_ref="2"/>
</object>
<object comment="objComment" flag="complete" id="objId" version="1">
<reference item_ref="1"/>
</object>
</collected_objects>
我使用下面的代碼 -
Document dom = parser.getDocument();
NodeList collected_objects = dom.getElementsByTagName("object");
System.out.println("Number of collected objects are " + collected_objects.getLength());
for (int i = 0; i < collected_objects.getLength(); i++) {
Node aNode = collected_objects.item(i);
//get children of "objects"
NodeList refNodes = aNode.getChildNodes();
System.out.println("# of chidren are " + refNodes.getLength());
//print attributes of "objects"
NamedNodeMap attributes = aNode.getAttributes();
for (int a = 0; a < attributes.getLength(); a++) {
Node theAttribute = attributes.item(a);
System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());
}
}
它輸出原樣
Number of collected objects are 2
# of chidren are 5
flag=complete
id=objId
version=1
# of chidren are 3
comment=objComment
flag=complete
id=objId
version=1
我的問題是,爲什麼它的處理「小孩的#」分別是5和3?我不應該分別期待2和1嗎? 因爲第一個對象具有「variable_value
」和「reference
」和第二個對象只有「reference
」
從本質上講,我的意圖是要處理「對象」的孩子。