I. 这是一种通用且强大的方法,可以在给定(增加)位置的情况下生成任何值的串联:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:strip-space elements="*"/>
<xsl:param name="pPositions" select="'|1|2|3|'"/>
<xsl:template match="value">
<xsl:if test="contains($pPositions, concat('|',position(),'|'))">
<xsl:value-of select="."/>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
当此转换应用于提供的 XML 文档时:
<root>
<level1>
<level2>
<value>A</value>
<value>B</value>
<value>C</value>
<value>D</value>
<value>E</value>
<value>F</value>
</level2>
</level1>
</root>
产生了想要的正确结果:
ABC
如果我们希望连接第 1、3 和第 6 个value
元素值,我们只需提供相应的$pPositions
参数:
<xsl:param name="pPositions" select="'|1|3|6|'"/>
同样的,未更改的 XSLT 代码现在产生了想要的:
ACF
二、如果我们有任何(不一定增加)位置序列,事情会变得更有趣:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:strip-space elements="*"/>
<xsl:param name="pPositions">
<p>4</p>
<p>1</p>
<p>3</p>
</xsl:param>
<xsl:variable name="vPositions" select=
"document('')/*/xsl:param[@name='pPositions']"/>
<xsl:template match="/">
<xsl:variable name="vDoc" select="."/>
<xsl:for-each select="$vPositions/p">
<xsl:value-of select="$vDoc/*/*/*/value[position()=current()]"/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
当应用于同一个 XML 文档(上图)时,我们得到了想要的正确结果:
DAC
三、这在 XSLT 2.0 中是微不足道的:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xsl:output method="text"/>
<xsl:strip-space elements="*"/>
<xsl:param name="pPositions" as="xs:integer*" select="4,1,3"/>
<xsl:template match="/">
<xsl:value-of separator="" select=
"for $n in $pPositions
return
/*/*/*/value[$n]
"/>
</xsl:template>
</xsl:stylesheet>