我有这个 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>
我正在尝试获取每个员工的子节点并放置子节点的标签值,即 列表中密码的标记值。
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);
}
}
我在调试时得到 children =4 的值。但我应该为每个循环得到它 2 请帮忙。
最佳答案
getChildNodes()
返回的 NodeList
包含 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);
}
关于xml - 如何在 Java 中使用 DOM 获取子节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11406105/