代码之家  ›  专栏  ›  技术社区  ›  JW.

XSLT字符串子位置

  •  0
  • JW.  · 技术社区  · 15 年前

    在XSLT2.0中,是否有一种简单的方法来替换字符串中的命名占位符?

    我在想一些类似于python的string.template的东西,在这里您可以这样做:

    d = dict(name='Joe', age='50')
    print Template("My name is $name and my age is $age").substitute(d)
    

    重点是将字符串外部化,这样就可以很容易地更改它。到目前为止,我找到的唯一方法是使用带参数的命名xsl:template,但这很冗长。有更简单的方法吗?

    2 回复  |  直到 15 年前
        1
  •  1
  •   Jim Garrison    15 年前

    没有关于python字符串模板顺序的高级功能,但是您可以使用xsl:analyze-string执行类似的操作,这样可以一次对一个字符串进行regex分析。如果希望replacements是表驱动的,可以设置xsl:key来存储映射,并编写xsl:function来对任意字符串执行替换。

    这不是世界上最简单的事情,但如果做得正确,以后肯定是可行和可重用的。

        2
  •  1
  •   JW.    15 年前

    我最后做了这样的事情:

    <!-- Reusable template to perform substitutions on a string -->
    <xsl:template name="substitutions">
        <!-- "string" is a string with placeholders surrounded by {} -->
        <xsl:param name="string" />
        <!-- "subs" is a list of nodes whose "key" attributes are the placeholders -->
        <xsl:param name="subs" />
        <xsl:analyze-string select="$string" regex="\{{(.*?)\}}">
            <xsl:matching-substring>
                <xsl:value-of select="$subs/sub[@key=regex-group(1)]" />
            </xsl:matching-substring>
            <xsl:non-matching-substring>
                <xsl:value-of select="." />
            </xsl:non-matching-substring>
        </xsl:analyze-string>
    </xsl:template>
    
    <!-- Example use of template -->
    <xsl:variable name="nameStr">My name is {name} and my age is {age}</xsl:variable>
    <xsl:call-template name="substitutions">
        <xsl:with-param name="string" select="$nameStr" />
        <xsl:with-param name="subs">
            <sub key="name">Joe</sub>
            <sub key="age">50</sub>
        </xsl:with-param>
    </xsl:call-template>
    

    我必须对替换名使用属性,而不仅仅是传递具有不同名称的节点(例如<name>joe</name>)。xpath(或者至少是saxon,我使用的处理器)似乎不允许像“$subs/regex group(1)”这样的动态表达式。但它允许“$subs/sub[@key=regex group(1)]”。