Pablo R.
Pablo R.

Reputation: 13

XPath compare child's value with parent's attribute

This is the XML context:

<?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>

I'm looking for the arrival of the city indicated by the CitySeq attribute of travel (CitySeq="2"). So what I need to match is seqno = CitySeq. The result I expect is <arrival>2015-04-20T20:35:00</arrival>.

This is working: /travel/cities/city[seqno=2]/arrival

But replacing the "2" is not: /travel/cities/city[seqno=/travel/@CitySeq]/arrival

Suggestions? (thanks in advance)

Upvotes: 1

Views: 461

Answers (2)

har07
har07

Reputation: 89285

Another alternative is using ancestor axis to get to the corresponding travel ancestor element.

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

This will help especially in the case when there are multiple travel elements in the root.

Upvotes: 1

Alin Pandichi
Alin Pandichi

Reputation: 955

EDIT: I tested the following expression at http://www.freeformatter.com/xpath-tester.html

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

I got a result:

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

OLD answer: I don't think XPath supports such embedded expressions. Your best bet is to do this in two steps. Pseudo-code follows (assuming Java):

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

Also, you should probably test against the possibility that the citySeq is not found in the first place.

Upvotes: 1

Related Questions