Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching for the first matching element after a specific node (XPath and ITunes XML)

it's not nessesary to post my full code because I have just a short questions. I'm searching with XPath in a XML Doc for a text Value. I have a XML Like

<key>Name</key>
<string>Dat Ass</string> 
<key>Artist</key>
<string>Earl Sweatshirt</string> 
<key>Album</key>
<string>Kitchen Cutlery</string> 
<key>Kind</key>
<string>MPEG-Audiodatei</string>

I have an Expression like this:

//string[preceding-sibling::key[text()[contains(., 'Name')]]]/text()

but this gives me ALL following string-tags, I just want the first one with the Song-Title.

greets Alex

like image 548
alex Avatar asked Nov 26 '25 19:11

alex


1 Answers

Use:

(//string[preceding-sibling::key[1] = 'Name'])[1]/text()

Alternatively, one can use a forward-only expression:

(//key[. = 'Name'])[1]/following-sibling::string[1]/text()

Do note:

This is a common error. Any expression of the kind:

//someExpr[1]

Doesn't select "the first node in the document from all nodes selected by //someExpr". In fact it can select many nodes.

The above expression selects any node that is selected by //someExpr and that is the first such child of its parent.

This is why, without brackets, the other answer to this question is generally incorrect.

like image 182
Dimitre Novatchev Avatar answered Nov 28 '25 07:11

Dimitre Novatchev