xml 如何在 Java 中使用 DOM 获取子节点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11406105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get childnodes using DOM in Java
提问by Aman
I have this XML.
我有这个 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>
I am trying to get the child nodes of each employee and put the tag value of child nodes i.e. password's tag value in a list.
我试图获取每个员工的子节点,并将子节点的标签值,即密码的标签值放在一个列表中。
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);
}
}
I am getting value of children =4 when I debug. But I should be getting it 2 for each loop Please help.
我在调试时得到了 children =4 的值。但我应该为每个循环得到 2 请帮忙。
回答by Dan O
the NodeListreturned by getChildNodes()contains Elementchild nodes (which is what you care about in this case) as well as attribute child nodes of the Nodeitself (which you don't).
在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);
}

