Stabbah
Stabbah

Reputation: 73

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?

Upvotes: 0

Views: 249

Answers (1)

har07
har07

Reputation: 89325

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

Upvotes: 1

Related Questions