用于元素集合的 XSLT for-each 循环

标签 xslt recursion loops foreach

是否可以在 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/

相关文章:

c - 找出循环中最大的数

python - 使用 BeautifulSoup 为每个子页面抓取数据 - url 很长且格式不同

java - Csv 文件循环工作错误

xslt - 使用 XSLT 记录日志

c++ - 增加递归函数中的数字

C++函数式编程代码片段

python - **recurPower** 我明白了,但我不明白

java - 使用 Java 的 XSLT

java - 修复XPath表达式中的绝对路径,以便它们可在另一个文档的上下文中使用

xslt - 如何在 XSLT 中进行 urlencode?