<xsl:stylesheet ... > <xsl:template match =" * " > <xsl:copy> <xsl:apply-templates /> </xsl:copy> </xsl:template> <xsl:template match=" thought " > <xsl:copy> <title><xsl:value-of select =" title " /><title> <xsl:apply-templates select =" author " /> <body><xsl:value-of select=" body " /><body> </xsl:copy> </xsl:template> <xsl:template match=" author " > <xsl:copy> <xsl:text>The author is: </xsl:text> <xsl:value-of select=" . " /> </xsl:copy> </xsl:template> </xsl:stylesheet>
XPath
- XSLT is crucially dependent on XPath for many functions
- XPath defines patterns for the match attribute of xsl:template:
<xsl:template match="thought/author" >
- XPath defines expressions for the select attribute of xsl:apply-templates:
<xsl:apply-templates select="author" />
- XPath defines expressions for the select attribute of xsl:value-of:
<creator><xsl:value-of select="author" />
- We will see that many template instructions also use XPath
- XPath expressions can yield values of type:
- Node-set (collection of nodes)
- Boolean value
- Number
- String
- Expression evaluation often occurs with respect to a context node
<xsl:template match="author"> ..... context node is the author node being processed <xsl:value-of select="."/> Selects the contents of the context node <xsl:value-of select="@xyz"/> The xyz attribute of the context node </xsl:template>
Example
- An example to show what XPath can do
- A hierarchy of nodes where each element either contains other elements or is empty
- There are no text nodes
<aaa><bbb><bbb><bbb><aa><aa><a /><g /><h /><h /></aa></aa></bbb> </bbb></bbb> <ccc><ccc /><ddd><ccc><aa /><bb><aa><h /><c /><e /><h /><e /><e /> <h /></aa><cc /><cc><g /><g /><f /><e /><f /></cc> </bb><bb /></ccc><ccc /><ddd /></ddd><ccc /></ccc><ddd><ddd /></ddd> <ccc><bbb /><ccc><ddd><cc /><cc><cc /><cc><h /><h /><e /><f /></cc> <bb /><dd /></cc><dd /><dd /><ee><dd><f /><f /><f /><d /><g /><c /></dd> </ee><ee /><ee /></ddd><ddd /> <eee><ff /><ff><ee /><ee><e /><e /><h /><f /><c /><h /><c /><d /></ee> <ee /><dd><b /><c /><d /><d /><d /><d /></dd> <cc /><aa /><bb /></ff><ee /><ee /><dd /></eee><ddd /> </ccc><eee /></ccc> <bbb><bbb><eee><cc><bb><g /><e /><e><h /><h /> <f /><f /><c /><f /><f /><h /></e><f /><c /> </bb></cc></eee></bbb></bbb></aaa>
You can search up and down the tree for nodes to change using various axes:
Starting from the highlighted cc node, something like this will select just the two c nodes at the bottom. XPath is a very powerful system for just changing the things that need to be changed.
XPath expressions get used for a variety of purposes in XSLT:
- XPath is a powerful tool for selecting which nodes to operate
- Used in four ways:
- match attribute determines which nodes a template applies to
- test attribute determines whether a condition applies
- select attribute selects a set of nodes for processing
- select attribute selects a value for processing
- XPath and XSLT functions defined to aid XPath in these activities