Accessing variables in recursive functions
I am creating a recursive XSLT function that run over all the Xml file child ..
<xsl:call-template name="testing">
<xsl:with-param name="root" select="ItemSet"></xsl:with-param>
</xsl:call-template>
While running the XSLT, I need to get the variable root node value, where I am
because when calling the root variable, I get the node with all the children node, but all I need is the single value of the node, and as it is recursive i can't act on the child node tags because it always changes. So how can I get the variable single specific value in anytime?
Neither $root
nor " . "
works.
XSL code:
<xsl:variable name="trial" select="count(./*)"></xsl:variable>
<xsl:choose>
<xsl:when test="count(./*) = 0">
:<xsl:value-of select="$root" /> <br/>
</xsl:when>
<xsl:otherwise>
<xsl:for-each sele开发者_如何转开发ct="./*">
<xsl:call-template name="testing">
<xsl:with-param name="root" select=".">
</xsl:with-param>
</xsl:call-template>
</xsl:for-each>
</xsl:otherwise>
</xsl:choose>
XML code :
<ItemSet>
<Item>
1
<iteml1>
1.1
</iteml1>
<iteml1>
1.2
</iteml1>
</Item>
<Item>
2
<iteml1>
2.1
<iteml2>
2.1.1
</iteml2>
</iteml1>
</Item>
</ItemSet>
what should if put as a code line in place of * so the solution would show:
1
1: 1.1 :
1: 1.2
2
2: 2.1
2: 2.1: 2.1.2
The wanted processing can be implemented efficiently and without explicit recursion:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes"/>
<xsl:template match="*[parent::*]">
<xsl:param name="pPath"/>
<xsl:value-of select="$pPath"/>
<xsl:variable name="vValue" select=
"normalize-space(text()[1])"/>
<xsl:value-of select="$vValue"/> <br/>
<xsl:apply-templates select="*">
<xsl:with-param name="pPath" select=
"concat($pPath, $vValue, ': ')"/>
</xsl:apply-templates>
</xsl:template>
<xsl:template match="text()"/>
</xsl:stylesheet>
When this transformation is applied on the provided XML document:
<ItemSet>
<Item>
1
<iteml1>
1.1
</iteml1>
<iteml1>
1.2
</iteml1>
</Item>
<Item>
2
<iteml1>
2.1
<iteml2>
2.1.1
</iteml2>
</iteml1>
</Item>
</ItemSet>
the wanted result is produced:
1<br/>1: 1.1<br/>1: 1.2<br/>2<br/>2: 2.1<br/>2: 2.1: 2.1.1<br/>
and it is displayed in the browser as:
1
1: 1.1
1: 1.2
2
2: 2.1
2: 2.1: 2.1.1
You have two choices: If this is only going to be used in one place, you could create a variable in the stylesheet root and use that globally.
Otherwise, what you'll need to do is have two parameters, one of which is passed exactly as is on each call, so as well as calling <xsl:with-param name="root" select="." />
, you also add <xsl:with-param name="baseroot" select="$baseroot" />
and define <xsl:param name="baseroot" select="$root" />
immediately below your <xsl:param name="root" />
. Then you can use $baseroot in place of $root anywhere that you need the original value that was passed in at the top of the stack.
精彩评论