Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The XPath id() function

I can't find any good explanation of the id() function in XPath. What does it do? How do you use it?

From the available descriptions, it sounds like it will give you id of a node.

So I played with it like this, but got an error:

//bookstore/id(book)

Then got a little fancier and tried

//bookstore/book[name = id(book/@category)]

which didn't return an error, but got no hits.

Can someone explain this function for me, and future Stack fans and Googlers?

Here's the XML I'm playing with:

<?xml version="1.0" encoding="ISO-8859-1"?>

<bookstore>

<book category="COOKING">
  <title lang="en">Everyday Italian</title>
  <author>Giada De Laurentiis</author>
  <year>2005</year>
  <price>30.00</price>
</book>

<book category="CHILDREN">
  <title lang="en">Harry Potter</title>
  <author>J. K. Rowling</author>
  <price>29.99</price>
</book>

<book category="WEB">
  <title lang="en">XQuery Kick Start</title>
  <author>James McGovern</author>
  <author>Per Bothner</author>
  <author>Kurt Cagle</author>
  <author>James Linn</author>
  <author>Vaidyanathan Nagarajan</author>
  <year>2003</year>
  <price>49.99</price>
</book>

<book category="WEB">
  <title lang="en">Learning XML</title>
  <author>Erik T. Ray</author>
  <year>2003</year>
  <price>39.95</price>
</book>

<book category="OPENSOURCE">
  <title lang="en">Open Source</title>
  <year>2003</year>
  <price>39.95</price>
</book>

<book category="WEB">
  <title lang="en">WEB</title>
  <year>2012</year>
  <price>21.99</price>
</book>

</bookstore>
like image 389
CodyBugstein Avatar asked Dec 25 '22 13:12

CodyBugstein


1 Answers

It appears that based on the spec that you would only use the id() function if you have defined unique IDs in your DTD.

The id function selects elements by their unique ID.

...

An element node may have a unique identifier (ID). This is the value of the attribute that is declared in the DTD as type ID.

I also came across this SO question that discusses the ID type in a DTD and how to define that.

like image 185
Matthew Green Avatar answered Jan 01 '23 09:01

Matthew Green