【发布时间】:2014-05-15 21:03:13
【问题描述】:
这里我在下面提到了我们通常在 Dom 节点上工作的方式。 我想找到一种方法来按名称调用特定节点,而无需像我评论代码那样遍历整个列表。
NodeList nodeList = _myDoc.getElementsByTagName("Parent");
// I want to get child2 node here calling by name without iterating over entire list
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getLocalName() != null) {
if (node.getLocalName().equals("child1")) {
// get node as child1
}else if (node.getLocalName().equals("child2")) {
// get node as child2
}etc...
}
}
注意:我知道这可以通过 XPath 完成。但我正在寻找 DOM 中的方法 这里 NodeList 表示 org.w3c.dom.NodeList,Node 表示 org.w3c.dom.Node。 (Get Node by Name from Nodelist中的回答提供了XPath解决方案)
【问题讨论】:
-
是吗?你的意思是我可以将 DOM NodeList 传递给 XPath 并获得一个 DOM 节点?
-
好的,抱歉,您正在尝试传递
NodeList,可能不好... -
是的。没关系。并感谢您的资源。