XPath将child的值与parent的属性进行比较

时间:2015-08-14 12:22:21

标签: xml xpath

这是XML上下文:

<?xml version="1.0" encoding="utf-8"?>
<root>
  <travel  Selectedcity="USPDX" CitySeq="2">
    <travelcode>01</travelcode>
    <cities>
      <city>
        <seqno>3</seqno>
        <city_code>USPDX</city_code>
        <arrival>2015-04-23T14:37:00.143</arrival>
      </city>
      <city>
        <seqno>1</seqno>
        <city_code>JPHIC</city_code>
        <arrival>2015-05-09T06:26:00</arrival>
      </city>
      <city>
        <seqno>2</seqno>
        <additional_code>11222</additional_code>
        <city_code>USPDX</city_code>
        <arrival>2015-04-20T20:35:00</arrival>
      </city>
    </cities>
  </travel>
</root>

我正在寻找CitySeq旅行属性所指示的城市的到来(CitySeq =“2”)。所以我需要匹配的是 seqno = CitySeq 。我期望的结果是<arrival>2015-04-20T20:35:00</arrival>

这是有效的:/travel/cities/city[seqno=2]/arrival

但是替换“2”不是:/travel/cities/city[seqno=/travel/@CitySeq]/arrival

连连呢? (提前谢谢)

2 个答案:

答案 0 :(得分:1)

编辑:我在http://www.freeformatter.com/xpath-tester.html

测试了以下表达式
/root/travel/cities/city[seqno=/root/travel/@CitySeq]/arrival

我得到了一个结果:

Element='<arrival>2015-04-20T20:35:00</arrival>'

OLD回答:我认为XPath不支持这样的嵌入式表达式。最好的办法是分两步完成。伪代码遵循(假设Java):

String citySeq = xPath.compile("/travel/@CitySeq").evaluate(xmlDocument);
String arrival = xPath.compile("/travel/cities/city[seqno="  + citySeq + "]/arrival").evaluate(xmlDocument);

此外,您可能应该测试首先找不到citySeq的可能性。

答案 1 :(得分:1)

另一种方法是使用ancestor轴来获取相应的travel祖先元素。

/root/travel/cities/city[seqno=ancestor::travel/@CitySeq]/arrival

如果travel中有多个root元素,这将有所帮助。