【问题标题】:Comma separated string parsing XSLT逗号分隔的字符串解析 XSLT
【发布时间】:2011-02-20 11:05:18
【问题描述】:

我如何循环遍历在 XSLT 1.0 中作为参数传递的逗号分隔字符串? 前-

<xsl:param name="UID">1,4,7,9</xsl:param>

我需要循环上面的 UID 参数并从我的 XML 文件中的每个 UID 中收集节点

【问题讨论】:

  • 好问题 (+1)。有关不涉及显式递归的解决方案,请参阅我的答案。

标签: xslt


【解决方案1】:

Vanilla XSLT 1.0 可以通过递归解决这个问题。

<xsl:template name="split">
  <xsl:param name="list"      select="''" />
  <xsl:param name="separator" select="','" />

  <xsl:if test="not($list = '' or $separator = '')">
    <xsl:variable name="head" select="substring-before(concat($list, $separator), $separator)" />
    <xsl:variable name="tail" select="substring-after($list, $separator)" />

    <!-- insert payload function here -->

    <xsl:call-template name="split">
      <xsl:with-param name="list"      select="$tail" />
      <xsl:with-param name="separator" select="$separator" />
    </xsl:call-template>
  </xsl:if>
</xsl:template>

有一些预构建的扩展库可以进行字符串标记化(例如,EXSLT 有一个模板),但我怀疑这里是否真的有必要。

【讨论】:

  • 你有没有string-join的递归模板?
【解决方案2】:

这是使用FXSLstr-split-to-words 模板的XSLT 1.0 解决方案。

请注意,此模板允许在多个分隔符上进行拆分(作为单独的参数字符串传递),因此即使使用此解决方案,1,4 7;9 也可以毫无问题地拆分。

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:ext="http://exslt.org/common"
>

   <xsl:import href="strSplit-to-Words.xsl"/>

   <xsl:output indent="yes" omit-xml-declaration="yes"/>

    <xsl:template match="/">
      <xsl:call-template name="str-split-to-words">
        <xsl:with-param name="pStr" select="/"/>
        <xsl:with-param name="pDelimiters"
                        select="', ;&#9;&#10;&#13;'"/>
      </xsl:call-template>
    </xsl:template>
</xsl:stylesheet>

当此转换应用于以下 XML 文档时

<x>1,4,7,9</x>

产生想要的正确结果

<word>1</word>
<word>4</word>
<word>7</word>
<word>9</word>

【讨论】:

  • 谢谢。循环这个逗号分隔参数的语法是什么?尝试了上述解决方案,但出现错误“找不到实现前缀'fxsl.sf.net'的脚本或外部对象。”我想我可能没有正确下载文件。好吧,我只需要将这个逗号分隔的字符串参数中的每个 id 值与 XML 节点 id 进行匹配,如果找到匹配项,则收集每个节点的文本以显示在输出 XML 中。请注意,我必须在 XSLT 1.0 中执行此操作。
  • @contactx:你的意思是你不能运行我的转换?您下载了 FXSL 1.x 吗? &lt;xsl:import&gt; 指令的 href 属性应指定库中模板的完整或相对路径。
猜你喜欢
  • 2012-01-20
  • 1970-01-01
  • 2019-12-04
  • 2021-11-01
  • 1970-01-01
  • 2020-06-12
  • 2015-05-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多