gpt4 book ai didi

Java-读取xml文件

转载 作者:行者123 更新时间:2023-11-30 03:52:31 25 4
gpt4 key购买 nike

在 Java 中,我使用 DocumentBuilderFactory、DocumentBuilder 和 Document 来读取 xml 文件。但现在我想创建一个方法,返回遵循给定节点序列的所有值的数组列表。为了更好地解释,我举一个例子:假设我有以下 xml 文件:

<one>
<two>
<three>5</three>
<four>6</four>
</two>
<two>
<three>7</three>
<four>8</four>
</two>
</one>

我使用带有字符串参数“one.two. Three”的方法,现在返回值应该是一个包含数字 5 和 7 的数组。

如何构建这个数组列表?

最佳答案

您可以使用 xpath,尽管语法与点略有不同(使用斜杠)

    Document d = ....

XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("/one/two/three/text()"); // your example expression
NodeList nl = (NodeList) expr.evaluate(d, XPathConstants.NODESET);
for (int i = 0; i < nl.getLength(); i++) {
String n = nl.item(i).getTextContent();
System.out.println(n); //now do something with the text, like add them to a list or process them directly
}

您可以找到有关如何使用 xpath here 查询节点的更多信息

关于Java-读取xml文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24066690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com