I have this input:
<school>
<faculty>
<area>
<name>F1A1</name>
</area>
<area>
<name>F1A2</name>
</area>
<area>
<name>F1A3</name>
</area>
</faculty>
<faculty>
<area>
<name>F2A1</name>
</area>
<area>
<name>F2A2</name>
</area>
<area>
<name>F2A3</name>
</area>
</faculty>
<faculty>
<area>
<name>F3A1</name>
</area>
<area>
<name>F3A2</name>
</area>
<area>
<name>F3A3</name>
</area>
</faculty>
</school>
and I want to get this output (the numbers in bracket is the string-length):
F1A1 (4)
F1A2 (4)
F1A3 (4)
F2A1 (4)
F2A2 (4)
F2A3 (4)
F3A1 (4)
F3A2 (4)
F3A3 (4)
Here are the requirements:
A. the initial match must be <xsl:template match="/">
.
B. a template T1 is defined as such:
<xsl:template name="T1">
<xsl:value-of select="concat(.,' (',string-length(.),') ')"/>
</xsl:template>
The script is required to call-template T1
to generate the required output, and T1 must not be altered in any way.
C. There must be no reliance on the default built-in template rules in XSLT.
This is my solution (it looks weird):
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" indent="yes"/>
<xsl:template match="/">
<xsl:for-each select="school/faculty">
<xsl:for-each select="area">
<xsl:for-each select="name">
<xsl:call-template name="T1"/>
</xsl:for-each>
</xsl:for-each>
</xsl:for-each>
</xsl:template>
<xsl:template name="T1">
<xsl:value-of select="concat(.,' (',string-length(.),') ')"/>
</xsl:template>
</xsl:stylesheet>
At one part, I'm using the <xsl:for-each select="name">
simply to change the current node
to name
, since I can't do a select
while call-template
. well i know, simply no one writes code this way since we will forego call-template
altogether and opt for apply-template
, but I'm just trying to solve this problem.
So, basically my question is, other than the <xsl:for-each select="name">
what other XSLT instructions can change the current node?
Bonus question: is there another way of solving the problem besides the way i'm doing it? (while respecting the 3 rules of course)
The answer is as per the comments. The instruction you need is xsl:template
(invoked by applying templates accordingly).
For instance, the following stylesheet produces the same result as your:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" indent="yes"/>
<xsl:template match="/">
<xsl:apply-templates select="school/faculty/area/name"/>
</xsl:template>
<xsl:template match="name">
<xsl:call-template name="T1"/>
</xsl:template>
<xsl:template name="T1">
<xsl:value-of select="concat(.,' (',string-length(.),') ')"/>
</xsl:template>
</xsl:stylesheet>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With