M
Martin Bright
I am trying to write an XSLT template which creates a subtree of an input
document, which is a simple tree. For example, the input might be
<node name="1"/>
<node name="2">
<node name="2.1"/>
<node name="2.2"/>
</node>
<node name="3"/>
I pass the template a parameter "2.2" and it creates the following result
fragment:
<node name="2">
<node name="2.2"/>
</node>
There is clearly one inefficient way of doing this:
<xsl:template match="node[.//node[@name='2.2']]">
<xsl:copy><xsl:apply-templates/></xsl:copy>
</xsl:template>
But it seems a shame to evaluate that XPath expression on each node. There
ought also to be a recursive way of doing it, like this:
<xsl:template match="node">
<xsl:choose>
<xsl:when test="@name='2.2'"><xsl:copy/></xsl:when>
<xsltherwise>
<xsl:variable name="children"><xsl:apply-templates/></xsl:variable>
<xsl:if test="$children">
<xsl:copy><xsl:copy-of select="$children"/></xsl:copy>
</xsl:if>
</xsltherwise>
</xsl:choose>
</xsl:template>
Unfortunately this doesn't work. The reason, AFAICT, is that the Boolean
value of a result tree fragment is always true, because it always contains a
hidden root node.
Can anybody either solve this particular problem of how to tell when a
result tree fragment is empty, or tell me a better way to approach this?
Many thanks
Martin Bright
document, which is a simple tree. For example, the input might be
<node name="1"/>
<node name="2">
<node name="2.1"/>
<node name="2.2"/>
</node>
<node name="3"/>
I pass the template a parameter "2.2" and it creates the following result
fragment:
<node name="2">
<node name="2.2"/>
</node>
There is clearly one inefficient way of doing this:
<xsl:template match="node[.//node[@name='2.2']]">
<xsl:copy><xsl:apply-templates/></xsl:copy>
</xsl:template>
But it seems a shame to evaluate that XPath expression on each node. There
ought also to be a recursive way of doing it, like this:
<xsl:template match="node">
<xsl:choose>
<xsl:when test="@name='2.2'"><xsl:copy/></xsl:when>
<xsltherwise>
<xsl:variable name="children"><xsl:apply-templates/></xsl:variable>
<xsl:if test="$children">
<xsl:copy><xsl:copy-of select="$children"/></xsl:copy>
</xsl:if>
</xsltherwise>
</xsl:choose>
</xsl:template>
Unfortunately this doesn't work. The reason, AFAICT, is that the Boolean
value of a result tree fragment is always true, because it always contains a
hidden root node.
Can anybody either solve this particular problem of how to tell when a
result tree fragment is empty, or tell me a better way to approach this?
Many thanks
Martin Bright