【问题标题】:XSLT 2 chain replaces?XSLT 2 链替换?
【发布时间】:2017-07-07 01:22:41
【问题描述】:

我需要在 XSLT 2 样式表中进行一系列替换。例如,我需要将所有出现的“aaa”替换为“bbb”,并将所有“ccc”替换为“ddd”。就正常的replace 通话而言,我应该有

<xsl:value-of select="replace(replace(text(), 'aaa', 'bbb'), 'ccc', 'ddd')"/>

但是,情况是我有数百个这样的替换对,为此我需要一个超长的select 属性。我想我可以使用例如 Python 脚本生成选择字符串,但它会很难看。有没有类似 XSLT 的东西

<xsl:replace from="aaa" to="bbb"/>
<xsl:replace from="ccc" to="ddd"/>
…

这样 XSLT 的可读性和可维护性更高(以及机器可操作)?

【问题讨论】:

    标签: xml xslt replace


    【解决方案1】:

    你必须创建一个可以替换每个术语的函数

    XSLT 2.0

        <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
        xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:funct="http://something"
        exclude-result-prefixes="xs"
        version="2.0">
    
        <xsl:template match="text()">
            <xsl:value-of select="funct:textreplace($replaces/replaces/rep, .)"/>
        </xsl:template>
    
    
        <xsl:param name="replaces">
            <replaces>
                <rep from="aaa" to="bbb"/>
                <rep from="ccc" to="ddd"/>
            </replaces>
        </xsl:param>
    
        <xsl:function name="funct:textreplace" as="xs:string">
            <xsl:param name="reps" as="element(rep)*"/>
            <xsl:param name="text" as="xs:string"/>
            <xsl:choose>
                <xsl:when test="not($reps)">
                    <xsl:value-of select="$text"/>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:value-of select="funct:textreplace($reps[position() gt 1], replace($text, $reps[1]/@from, $reps[1]/@to))"/>
                </xsl:otherwise>
            </xsl:choose>
        </xsl:function>
    
    </xsl:stylesheet>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-08
      • 1970-01-01
      • 1970-01-01
      • 2011-03-05
      • 1970-01-01
      • 2014-07-26
      • 2020-05-21
      相关资源
      最近更新 更多