正确的XPathExpression来检索Java中的节点?

时间:2018-06-22 10:26:13

标签: java xpath

我有一个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:HourlyHistoricalPrice特定值的hhp:refSource节点,例如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());

如果有人可以提供使用正确表达的建议,我将不胜感激。

非常感谢。

1 个答案:

答案 0 :(得分:1)

您需要将前缀扩展为它代表的xml名称空间:

.dialog_animate {
  animation: dialog_animate 5s ease-in-out forwards;
  -webkit-animation: dialog_animate 5s ease-in-out forwards;
}

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

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

输出“ 2”。

相关问题