简体   繁体   中英

XPath selecting the mother node while in a child node

So I'm trying to solve the query: "Find the names of the ships that were sunk"

and "Find the names of all the ships that were in battles"

but I'm having some problems.

I have this XML document:

<Ships>
  <Class name="Kongo" type="be" country="Japan" numGuns="8" bore="14" displacement="32000">
    <Ship name="Kongo" launched="1913"/>
    <Ship name="Hiei" launched="1914"/>
    <Ship name="Kirishima" launched="1915">
      <Battle outcome="sunk">Guadalcanal</Battle>
    </Ship>
    <Ship name="Haruna" launched="1915"/>
  </Class>

And for "Find the names of the ships that were sunk" I try:

Ships/Class/Ship/Battle[@outcome = 'sunk']

and get:

<Battle outcome="sunk">Guadalcanal</Battle>
<Battle outcome="sunk">Malaya</Battle>

But that is not the right result, is it. I don't know how to select the ship names while choosing the battle outcome or selecting the ships that were in battles. How do I do this?

Try this way to get " Ships that were sunk " :

Ships/Class/Ship[Battle/@outcome = 'sunk']

Make element you want to select as the last element in the path, and make criteria for that element within square brackets.

Or this way to get ship's name :

Ships/Class/Ship[Battle/@outcome = 'sunk']/@name

And to get all <Ship> element that has child <Battle> then select the ship's name, in short " Find names of all the ships that were in battles " :

Ships/Class/Ship[Battle]/@name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM