Tutorial: Programming with xsl
Zoo tutorials:
[
SQL
|
Java
|
Linux
|
XML
]
A Gentle Introduction to
xml
Programming with xsl
Question 1: Parameters and call-template.
Here we call with parameter s. At each to rev we either
return the string s unchanged (if it has no spaces)
output the word then recurse with everything but the first word
Note the
<text>
element. Change this so that - is used in place of a space.
XML
<string>This is a string of text</string>
XSL
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <reversed> <xsl:call-template name="rev"> <xsl:with-param name="s" select="/string"/> </xsl:call-template> </reversed> </xsl:template> <!-- copy the input --> <xsl:template name="rev" > <xsl:param name="s"/> <xsl:choose> <xsl:when test="contains($s,' ')"> <xsl:value-of select="substring-before($s,' ')"/> <xsl:text> </xsl:text> <xsl:call-template name="rev"> <xsl:with-param name="s" select="substring-after($s,' ')"/> </xsl:call-template> </xsl:when> <xsl:otherwise> <xsl:value-of select="$s"/> </xsl:otherwise> </xsl:choose> </xsl:template> </xsl:stylesheet>
Show as text
Question 2: map string-length.
Change the code so that it returns the length of each word. we should get the string 4 2 1 6 2 4 returned. You may use the function
string-length
.
XML
<string>This is a string of text</string>
XSL
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <reversed> <xsl:call-template name="rev"> <xsl:with-param name="s" select="/string"/> </xsl:call-template> </reversed> </xsl:template> <!-- copy the input --> <xsl:template name="rev" > <xsl:param name="s"/> <xsl:choose> <xsl:when test="contains($s,' ')"> <xsl:value-of select="substring-before($s,' ')"/> <xsl:text> </xsl:text> <xsl:call-template name="rev"> <xsl:with-param name="s" select="substring-after($s,' ')"/> </xsl:call-template> </xsl:when> <xsl:otherwise> <xsl:value-of select="$s"/> </xsl:otherwise> </xsl:choose> </xsl:template> </xsl:stylesheet>
Show as text
Question 3: So that's why it's called rev!
Reverse the order of the three nodes
xsl:call-template
xsl:text
xsl:value-of
This should cause the string to be returned reversed.
XML
<string>This is a string of text</string>
XSL
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <reversed> <xsl:call-template name="rev"> <xsl:with-param name="s" select="/string"/> </xsl:call-template> </reversed> </xsl:template> <!-- copy the input --> <xsl:template name="rev" > <xsl:param name="s"/> <xsl:choose> <xsl:when test="contains($s,' ')"> <xsl:value-of select="substring-before($s,' ')"/> <xsl:text>-</xsl:text> <xsl:call-template name="rev"> <xsl:with-param name="s" select="substring-after($s,' ')"/> </xsl:call-template> </xsl:when> <xsl:otherwise> <xsl:value-of select="$s"/> </xsl:otherwise> </xsl:choose> </xsl:template> </xsl:stylesheet>
Show as text