Select a node with a unique identifier using XSLT

How can I select a specific node with a unique identifier and return the entire node as xml.

<xml> <library> <book id='1'> <title>firstTitle</title> <author>firstAuthor</author> </book> <book id='2'> <title>secondTitle</title> <author>secondAuthor</author> </book> <book id='3'> <title>thirdTitle</title> <author>thirdAuthor</author> </book> </library> </xml> 

In this case, I would like to return the book with id = '3', so it will look something like this:

 <book id='3'> <title>thirdTitle</title> <author>thirdAuthor</author> </book> 
+4
source share
5 answers

This stylish XSLT table 1.0 ...

 <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes"/> <xsl:template match="/"> <xsl:apply-templates select="*/*/book[@id='3']" /> </xsl:template> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()" /> </xsl:copy> </xsl:template> </xsl:stylesheet> 

... converts your sample input document to the specified sample output document

+4
source

If you reference XPath (because you are looking in the document, not its conversion), this will be:

 //book[@id=3] 

Of course, depending on your language, there may be a library that makes this search even easier.

+2
source

In XSLT, you use xsl:copy-of to paste the selected node into the result tree:

 <xsl:copy-of select="/*/library/book[@id=3]"/> 
+1
source

The most efficient * and readable way to do this is via key :

 <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- To match your expectation and input (neither had <?xml?> --> <xsl:output method="xml" omit-xml-declaration="yes" /> <!-- Create a lookup for books --> <!-- (match could be more specific as well if you want: "/xml/library/book") --> <xsl:key name="books" match="book" use="@id" /> <xsl:template match="/"> <!-- Lookup by key created above. --> <xsl:copy-of select="key('books', 3)" /> <!-- You can use it anywhere where you would use a "//book[@id='3']" --> </xsl:template> </xsl:stylesheet> 

* For 2142 points and 121 searches, he made a difference of 500 milliseconds, which was 33 times the general acceleration in my case. Measured against //book[@id = $id-to-look-up] .

0
source

take a look at SimpleXML xpath

xpath simpleXML

-2
source

All Articles