0
votes

How do i select the element value that contain specific attribute from another element ?

I have tried //artist[@country='USA']/title but it return no result

Below is the structure of how my xml look like

<?xml version="1.0" encoding="UTF-8"?>
<catalog>
 <cd>
 <title>I DON'T WANT TO MISS A THING</title>
 <artist country="USA">AEROSMITH</artist>
 <price>9.90</price>
 <year>1998</year>
 </cd>
 <cd>
 <title>(EVERYTHING I DO) I DO IT FOR YOU</title>
 <artist country="CANADA">BRYAN ADAMS</artist>
 <price>10.20</price>
 <year>1991</year>
 </cd>
</catalog>

expected output showing title that have artist from the country USA

2

2 Answers

1
votes

The title isn't a child of the artist, but a child of its parent:

//artist[@country='USA']/../title

Or, if title always precedes artist, you can use

//artist[@country='USA']/preceding-sibling::title
1
votes

It's harder to see because your XML is not indented, but you're looking at "cd" elements.

This is the XPath I would use :

/catalog/cd[artist/@country='USA']/title