我有这个XML.
<employees>
<employee tag="FT" name="a">
<password tag="1"/>
<password tag="2"/>
</employee>
<employee tag="PT" name="b">
<password tag="3"/>
<password tag="4"/>
</employee>
</employees>
Run Code Online (Sandbox Code Playgroud)
我正在尝试获取每个员工的子节点,并将子节点的标记值(即密码的标记值)放在列表中.
nl = doc.getElementsByTagName("employee");
for(int i=0;i<nl.getLength();i++){
NamedNodeMap nnm = nl.item(i).getAttributes();
NodeList children = nl.item(i).getChildNodes();
passwordList = new ArrayList<String>();
for(int j=0; j<children.getLength();j++){
NamedNodeMap n = children.item(j).getAttributes();
passwordTagAttr=(Attr) n.getNamedItem("tag");
passwordTag=stopTagAttr.getValue();
passwordList.add(passwordTag);
}
}
Run Code Online (Sandbox Code Playgroud)
我调试的时候,我得到的孩子值= 4.但我应该为每个循环得到它2请帮助.
Dan*_*n O 10
在NodeList通过返回getChildNodes()包含Element子节点(这是你在这种情况下,所关心的事),以及该属性子节点Node(你没有)本身.
for(int j=0; j<children.getLength();j++) {
if (children.item(j) instanceof Element == false)
continue;
NamedNodeMap n = children.item(j).getAttributes();
passwordTagAttr=(Attr) n.getNamedItem("tag");
passwordTag=stopTagAttr.getValue();
passwordList.add(passwordTag);
}
Run Code Online (Sandbox Code Playgroud)