是否可以在 XSLT 中创建一个 for-each 循环而不是针对节点集,而是针对我自己的元素集合?例如,我拆分了一些字符串并得到了一个字符串集合。我需要为集合中的每个项目创建一个节点。我知道这个问题可以用递归模板解决,但我想知道是否可以避免递归。
最佳答案
有两种明显、直接的解决方案,其中一种仅在 XSLT 2.0 中受支持:
我。通用解决方案
这适用于 XSLT 1.0 和 XSLT 2.0。
定义您自己的命名空间并将您的节点集作为此命名空间中元素的子元素放置,该元素全局放置在样式表中(<xsl:stylesheet>
指令的子元素。)
这是一个例子:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:my="my:my" exclude-result-prefixes="my"
>
<xsl:output method="text"/>
<my:nodes>
<string>Hello </string>
<string>World</string>
</my:nodes>
<xsl:variable name="vLookup"
select="document('')/*/my:nodes/*"/>
<xsl:param name="pSearchWord" select="'World'"/>
<xsl:template match="/">
<xsl:if test="$pSearchWord = $vLookup">
<xsl:value-of select=
"concat('Found the word ', $pSearchWord)"/>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
当此转换应用于任何 XML 文档(未使用)时,结果是:
Found the word World
请注意我们不需要 xxx:node-set()
完全没有扩展功能。
二。 XSLT 2.0/XPath 2.0 解决方案
在 XSLT 2.0/XPath 2.0 中,总是可以使用 sequence 类型。例如,可以通过这种方式简单地定义一个变量来包含一系列字符串:
<xsl:variable name="vLookup" as="xs:string*"
select="'Hello', 'World'"/>
并在以下转换中使用它:
<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:variable name="vLookup" as="xs:string*"
select="'Hello', 'World'"/>
<xsl:param name="pSearchWord" select="'World'"/>
<xsl:template match="/">
<xsl:if test="$pSearchWord = $vLookup">
<xsl:value-of select=
"concat('Found the word ', $pSearchWord)"/>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
关于用于元素集合的 XSLT for-each 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2779660/