0
votes

I have a bunch of nodes like this:

<root>
   <books>
      <book id="1">Book 1</book>
      <book id="2">Book 2</book>
      <book id="3">Book 3</book>
   </books>
</root>

What I want is to get the id of the book with text node "Book 2". How do I do this? I tried this without any result ($doc is my document path):

let $b := $doc/root/books/book[book = "Book 2"]
return data($b/@id)

EDIT: I meant that $doc is the document node, not only the path.

2

2 Answers

2
votes

Assuming that $doc is in fact a document-node and not a document path as you described it then you can use the following:

$doc/root/books/book[. = "Book 2"]/data(@id)

Simply put . refers to the current context item, which is already book as that is the last part of the XPath before the predicate.

1
votes

if $doc is your document path, you'll need to call fn:doc($doc), to get the document-node:

fn:doc($doc)/root/books/book[. = "Book 2"]/data(@id)