Absolute and Relative Path in XSLT

The following is observed from xslt version 1.0

1. There are two important nodes that we must always be sure about

“.” the current context node and
“/” document root not current context node root

“.” Context node can be changed while getting in and out of looping : xsl:for-each or xsl:apply-templates, in some circumstances “/” document root could also be changed.

2. Even within a for-each loop, you still can select elements out side of context node by using absolute path. like select=”/abolute level1/absolute level2″

3.How to tell the path is absolute or relative, there are only two ways for absolute path:

Absolute path 1: starts from “/”, select=”/abolute level1/absolute level2″

Absolute path2: abbreviated absolute location path, starts from “//”, select =”//absolute levelx from root/levely”, this is sometime confusing, as it could be deemed as context node downward searching rather than document root based downward searching.

Anything else is relative location path, you can explicitly use “.” to indicate that this is a relative location path to current context node select=”./childlevel1/childlevel2″ which is the same as “childlevel1/childlevel2”
or select “.//childlevel2”

But bear in mind, document has context too, in the following case, the document inside the for-each is switched from the one outside of for-each

<xsl:variable name="nodeset">
            <xsl:copy-of select="//Groups/Group"/>
<xsl:for-each select="msxsl:node-set($nodeset)/*">
            <xsl:variable name="whatisthis" select="." />
            <xsl:variable name="whatisthis2" select="/" />

Whatisthis2 is the root of new document created by node-set conversion, rather than the root of “//Groups/Group”, copy-of only returns a result tree fragment , so needs to be converted into node-set to use xpath

Key() use:

key() function always selects nodes from the same document the context node belongs to, that means index is only built when first time key is used, and has a document context, so be careful when first reference of key is called, the document context will be decided by then, not where you declare your key. So you can see difference in above example if key is called within the for-each $nodeset loop or out side loop.

Ways to avoid confusion:

Always be aware of context change in terms of both node and document
Try not to use node-set extension function.



This entry was posted on Friday, August 19th, 2011 at 11:08 pm and is filed under ASP.NET, Java. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply