【问题标题】:XSLT Translate IssueXSLT 翻译问题
【发布时间】:2019-02-02 14:31:54
【问题描述】:

我在 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 的一个非常基本的示例部分,用于测试标题元素中的 [remove this text] 字符串(此函数嵌套在 for-each 循环中):

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

这成功地删除了不需要的字符串,并且在大多数情况下保留了前面的文本而不会出现问题。不幸的是,在少数问题中,title 元素的结果输出将丢失几个字符(所有空格都被删除)并且看起来像“kpptt2”而不是“Keep this text 2”。有谁知道为什么会发生这种情况和/或产生像这个例子这样的侥幸?谢谢!

【问题讨论】:

  • 您将translate()replace() 混淆了。 translate() 用其他字符替换单个字符。 replace()(在 XSLT 1.0 中不存在)用另一个字符串替换一个字符串。
  • 了解 translate() 不是理想的解决方案,但是在 XML 1.0 中是否有更好的方法来处理这个问题?

标签: xml xslt


【解决方案1】:
    <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版使用

【讨论】:

  • 谢谢,使用 substring-before() 得到了我需要的东西。谢谢!
【解决方案2】:
    <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+\s\w+\s\w+\]', '')"/>
</xsl:template>

请检查

【讨论】:

    【解决方案3】:
        <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\[remove\sthis\stext\]', '')"/>
    </xsl:template>
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-11
      • 2013-05-03
      • 2012-10-27
      • 2021-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多