关于java:Nodelist到arraylist 的转换

Nodelist to arraylist conversion

我已经提取了节点列表,
this.NodeList xml = doc.getElementsByTagName(tagName)

现在我想将xml转换为ArrayList类型,有什么建议吗?


关于Java

从Java 8开始,您可以使用IntStream和map,其中nodeList是NodeList的实例:

1
2
3
4
List<String> nodeNames = IntStream.range(0, nodeList.getLength())
        .mapToObj(nodeList::item)
        .map(n -> n.getNodeName())
        .collect(Collectors.toList());

这会将节点的名称收集到一个列表中。

为了更通用,可以收集Node元素,然后对其进行处理:

1
2
3
List<Node> nodes = IntStream.range(0, nodeList.getLength())
        .mapToObj(nodeList::item)
        .collect(Collectors.toList());

请注意,从Java 10开始,您还可以仅var而不是List

1
2
3
var nodes = IntStream.range(0, nodeList.getLength())
        .mapToObj(nodeList::item)
        .collect(Collectors.toList());

1
var nodeArrayList = new ArrayList(xmlNodeList.OfType<XmlNode>().ToList());