XSLT 翻译问题



我在 xslt 脚本中使用 translate(( 函数在渲染输出之前从重复元素中删除不需要的字符串。虽然翻译功能正在发挥作用,但它通过删除比应有的字符更多的字符来影响其中的少数元素,我一生都无法弄清楚为什么会发生这种情况。

下面是一个示例 XML 文档:

<?xml version="1.0" encoding="utf-8"?><books><book><title>Keep this text [remove this text]</title></book><book><title>Keep this text 2 [remove this text]</title></book><book><title>Keep this text 3 [remove this text]</title></book><book><title>Keep this text 4</title></book></books>

下面是 XSLT 的一个非常基本的示例部分,用于测试标题元素中的 [删除此文本] 字符串(此函数嵌套在 for-each 循环中(:

<xsl:value-of select="translate(books/book/title, '[remove this text]', '')" />

这将成功删除不需要的字符串,并且在大多数情况下可以毫无问题地保留前面的文本。不幸的是,在少数问题中,title 元素的最终输出将缺少几个字符(所有空格都将被删除(,并且看起来像"kpptt2"而不是"保留此文本 2"。有没有人知道为什么会发生这种情况和/或产生像这个例子这样的侥幸?谢谢!

    <xsl:template match="node() | @*">
    <xsl:copy>
        <xsl:apply-templates select="node() | @*"/>
    </xsl:copy>
</xsl:template>
<xsl:template match="*/text()">
    <xsl:choose>
        <xsl:when test="contains(., '[remove this text]')">
            <xsl:value-of select="substring-before(., ' [remove this text]')"/>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="."/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

版本 1.0 使用

    <xsl:template match="node() | @*">
    <xsl:copy>
        <xsl:apply-templates select="node() | @*"/>
    </xsl:copy>
</xsl:template>
<xsl:template match="//text()">
    <xsl:value-of select="replace(., 's[w+sw+sw+]', '')"/>
</xsl:template>

请检查

    <xsl:template match="node() | @*">
    <xsl:copy>
        <xsl:apply-templates select="node() | @*"/>
    </xsl:copy>
</xsl:template>
<xsl:template match="//text()">
    <xsl:value-of select="replace(., 's[removesthisstext]', '')"/>
</xsl:template>

代码特定文本"[删除此文本]"删除

最新更新