使用什么代替 nodeSet

what to use instead of nodeSet

我有一个函数需要编译 NodeList,它需要使用 NodeList,因为我也使用 xpath 生成 NodeList 并处理结果。

我的密码是

NodeSet nodes = new NodeSet();

NodeList children = mainElement.getChildNodes();
for(int i=0;i<children.getLength();i++){
    Node child = children.item(i);
    if(nodeName==null || child.getNodeName().equals(nodeName)){
        if(attName==null){
            //if not att name then all nodes
            nodes.addNode(child);
        }
    }
}

我可以自己写 class,但我原以为已经有一些东西可以用于此目的?

注意,如果您要降价,请在评论中说明原因,以便我日后更正。

如果你在Java 8:

中这样做,也许生活会更好
IntStream.range(0, children.getLength())
    .map(children::item)
    .filter(child -> child.getNodeName().equals(nodeName))
    .collect(Collectors.toList());

我想没有一个框架方法来做这类事情的原因是每个消费者希望做的遍历可能完全不同。

您确实也可以使用 XPath 来构建您的结果。 就目前而言,您的代码抓取 "all nodes of name nodeName that are direct children of the mainElement node".

如果它是在 mainElement 的上下文中计算的,则转换为 nodeName XPath 表达式。这很简单:

XPath nodeNameXPath = XPathFactory.newInstance().newXPath().compile(nodeName)
NodeList result = (NodeList) nodeNameXPath.eval(mainElement, XPathConstants.NODESET)

这应该可以做到。