xsl-list
[Top] [All Lists]

Re: [xsl] Best performant way to selectively find and process one node

2007-05-20 14:01:17
On 5/20/07, Luhar P <luharp(_at_)gmail(_dot_)com> wrote:
Hi,

I am newbie to xslt, so please excuse me if this sounds naive. Though
I know one way to get what i want, but i would like a more performant
way to do it.

I have need to find and process only one node out of thousands and
generate output for it.
The node needs to be selected based upon querystring value for book id
and then processed by a template.

A simplified book structure is given below -

<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<books>
 <book>
   <bookId>1</bookId>
   <title lang="eng">Harry Potter</title>
   <price>29.99</price>
 </book>
 <book>
   <bookId>2</bookId>
   <title lang="eng">Learning XML</title>
   <price>39.95</price>
 </book>
</books>
</bookstore>

One (IMO) non performant way of doing it is to have a template that
matches books, select book with the correct id and pass it for
processing to named template.
I am sure there is way to avoid matching all book nodes and then find
the correct node to pass to named template.

For simplicity sake, i am assuming that the querystring book id value
gets set in xslt variable (using xslt extensions) but right now is
hardcoded to value 1.
<xslt:variable name="book_id" select="1">

<xslt:template match="book">
 <xslt:call-template name="GetBookDetails" >
   <xslt:with-param name="book_node" select
="bookstore/books/book[id=$book_id]"></xslt:with-param>
 </xslt:call-template >
  </xslt:template>

Ideally, i would like to be able to do something like
<xslt:template match="bookstore/books/book[id=$book_id]">
   <xslt:apply templates/>
</xslt:template>
But i can not use vairables in match statement. I did search on
biglist and other places, but could not find related question.
I am sure this is very common scenario and i am missing something.

Use:

<xsl:template match="/">
 <xsl:apply-templates select="/bookstore/books/book[id=$book_id]"/>
 ...

with:

<xsl:template match="book"/>

This way you only select the nodes you want to process.

To speed up repeated access use a key, eg:

<xsl:key name="books-by-id" match="book" use="bookId"/>

<xsl:apply-templates select="key('books-by-id', $book_id)"/>

but if you have 1 large file like that then an XML database might be
more suitable your needs - have you looked at any yet?

cheers
andrew

--~------------------------------------------------------------------
XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list
To unsubscribe, go to: http://lists.mulberrytech.com/xsl-list/
or e-mail: <mailto:xsl-list-unsubscribe(_at_)lists(_dot_)mulberrytech(_dot_)com>
--~--