xml - 如何在 Java 中使用 DOM 获取子节点

标签 xml dom

我有这个 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/

相关文章:

javascript - ReactJS - 在 React 类中初始化 jquery 插件的标准方法是什么?

javascript - HTMLCollections 可以用 for...of (Symbol.iterator) 迭代吗?

javascript - 很想从 .getElementsByTagName 获取属性吗?

php - curl 不适用于我的连接的 linkedin 配置文件

java - XMLUnit - 比较时忽略 'id' 属性

android - 在自定义警报对话框中显示 map

xml - 使用未知大小的数组中的项目作为选项在 powershell 中创建菜单

xml - 将 xml 标签名称提取到 xml 属性值中

c# - 数据绑定(bind)到 WinForm

javascript - IE 对 HTMLDocument 和 HTMLElement 有什么看法