首页 > 解决方案 > 在 xslt 1.0 中,如何使用 replace() 函数的替代方法

问题描述

输入xml代码:

<Job>
<Telephone> 123/ 345-566 | 456-394-798 | (234)-453-245 </Telephone>
</Job>

输出xml代码:

<Job>
<PhoneAreaCode> 123|456|234 </PhoneAreaCode>
</Job>

我已经使用带有正则表达式的 replace() 函数编写了一个 xslt 2.0 文件,以实现我的输出 xml。但是我的 VisualStudio 只支持 xslt 1.0。

你能帮我写一个输出xml代码的xslt代码吗?

注意:我需要将123|456|234存储在一个全局变量中,以便可以在输出 xml 文件中的各种情况下使用它。

提前致谢。

标签: xmlxsltxslt-1.0

解决方案


单个示例通常不足以可靠地推断出需要应用的逻辑以处理所有可能的场景。

查看您提供的示例,在我看来,这里真正的问题不是如何replace(),而是如何tokenize()

考虑以下样式表:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="Telephone">
    <PhoneAreaCode>
        <xsl:call-template name="tokenize-and-extract">
            <xsl:with-param name="text" select="."/>
        </xsl:call-template>
    </PhoneAreaCode>
</xsl:template>

<xsl:template name="tokenize-and-extract">
    <xsl:param name="text"/>
    <xsl:param name="delimiter" select="'|'"/>
        <xsl:variable name="token" select="substring-before(concat($text, $delimiter), $delimiter)" />
        <xsl:if test="$token">
            <xsl:value-of select="substring(translate($token, ' /()-', ''), 1, 3)"/>
        </xsl:if>
        <xsl:if test="contains($text, $delimiter)">
            <!-- recursive call -->
            <xsl:text>|</xsl:text>
            <xsl:call-template name="tokenize-and-extract">
                <xsl:with-param name="text" select="substring-after($text, $delimiter)"/>
            </xsl:call-template>
        </xsl:if>
</xsl:template>

</xsl:stylesheet>

应用于您的示例输入 XML,结果将是:

<Job>
  <PhoneAreaCode>123|456|234</PhoneAreaCode>
</Job>

推荐阅读