gpt4 book ai didi

java - 在 Java 中检索节点的 XPathExpression 是否正确?

转载 作者:行者123 更新时间:2023-12-02 11:05:41 27 4
gpt4 key购买 nike

我有一个 XML 文档,其中包含多个 hpp:HourlyHistoricalPrice 元素,如下所示:

<?xml version="1.0">
<hhp:HourlyHistoricalPrices xmlns:hhp="urn:or-HourlyHistoricalPrices">
<hhp:HourlyHistoricalPrice xmlns:hhp="urn:or-HourlyHistoricalPrice">
<hhp:indexId>1025127</hhp:indexId>
<hhp:resetDate>20161231T000000</hhp:resetDate>
<hhp:refSource>AIBO</hhp:refSource>
<hhp:indexLocation/>
<hhp:price1>50,870000</hhp:price1>
...
<hhp:price48>43,910000</hhp:price48>
</hhp:HourlyHistoricalPrice>
<hhp:HourlyHistoricalPrice xmlns:hhp="urn:or-HourlyHistoricalPrice">
<hhp:indexId>1025127</hhp:indexId>
<hhp:resetDate>20160101T000000</hhp:resetDate>
<hhp:refSource>AIBO</hhp:refSource>
<hhp:indexLocation/>
<hhp:price1>51,870000</hhp:price1>
...
<hhp:price48>49,910000</hhp:price48>
</hhp:HourlyHistoricalPrice>
<hhp:HourlyHistoricalPrice xmlns:hhp="urn:or-HourlyHistoricalPrice">
<hhp:indexId>1025127</hhp:indexId>
<hhp:resetDate>20163112T000000</hhp:resetDate>
<hhp:refSource>APX</hhp:refSource>
<hhp:indexLocation/>
<hhp:price1>63,870000</hhp:price1>
...
<hhp:price48>29,910000</hhp:price48>
</hhp:HourlyHistoricalPrice>
</hhp:HourlyHistoricalPrices>

我只想检索具有 hhp:refSource 特定值的 hhp:HourlyHistoricalPrice 节点,例如AIBO

我尝试了下面的 XPathExpression,但这什么也没检索到。

 XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();

String strExprssion =
"/hhp:HourlyHistoricalPrices/hhp:HourlyHistoricalPrice[hhp:refSource='AIBO']";

XPathExpression expression = xpath.compile(strExprssion);

NodeList nodes = (NodeList) expression.evaluate(originalXmlDoc, XPathConstants.NODESET);

System.out.println(nodes.getLength());

如果有人能够提供有关正确使用表达方式的建议,我将不胜感激。

非常感谢。

最佳答案

您需要将前缀扩展到它所代表的 xml 命名空间中:

String strExprssion = "//urn:or-HourlyHistoricalPrice:HourlyHistoricalPrice[urn:or-HourlyHistoricalPrice:refSource='AIBO']";

所以对我来说,这个测试类

public class XPathCheck {
public static void main(String[] args) throws FileNotFoundException, IOException, XPathExpressionException {
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();

try (InputStream file = new FileInputStream(Paths.get("src", "inputFile.xml").toFile())) {
String strExprssion = "//urn:or-HourlyHistoricalPrice:HourlyHistoricalPrice[urn:or-HourlyHistoricalPrice:refSource='AIBO']";
XPathExpression expression = xpath.compile(strExprssion);
NodeList nodes = (NodeList) expression.evaluate(new InputSource(file), XPathConstants.NODESET);

System.out.println(nodes.getLength());
}
}
}

输出“2”。

关于java - 在 Java 中检索节点的 XPathExpression 是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50985914/

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