我知道这比它看起来更简单,但我无法理解......
如何迭代两个Java NodeList集合以查看是否存在匹配。
EG:
NodeList NODE1 = doc1.getElementsByTagName("tag1");
NodeList NODE2 = doc2.getElementsByTagName("tag2");
我想迭代NODE1
和NODE2
,看看2个标签中是否有匹配的数据。我有Java基础知识,并且我是XML方面的新手,因此非常感谢任何帮助。
答案 0 :(得分:0)
尝试一下以下内容:
public Collection<Node> getMatchingNodes(NodeList n1, NodeList n2, Class<? extends Node> typeToMatch){
Collection<Node> n1Nodes = getNodes(n1, typeToMatch);
Collection<Node> n2Nodes = getNodes(n2, typeToMatch);
n1Nodes.retainAll(n2Nodes);
return n1Nodes;
}
private Collection<Node> getNodes(NodeList nodeList, Class<? extends Node> typeToMatch){
Collection<Node> n1Nodes = new ArrayList<>();
for(int i = 0; i < nodeList.getLength(); i++){
if(nodeList.item(1).getClass() == typeToMatch){
n1Nodes.add(nodeList.item(i));
}
}
return n1Nodes;
}
请注意,这只会比较相同类型的节点,例如文本。