【问题标题】:How can I strip trailing full stop (period) from text nodes如何从文本节点中去除尾随句号(句点)
【发布时间】:2021-05-08 19:36:59
【问题描述】:

如果我有一个带有句号结尾的文本节点(或美国英语中的句点),我可以使用什么表达式来去掉句号并保留其余部分?

例如输入

<ol>
<li>This is the first item.</li>
<li>This is the second</li>
<li>This is the 3rd. </li>
</ol> 

需要的输出

<ol>
<li>This is the first item</li>
<li>This is the second</li>
<li>This is the 3rd</li>
</ol>  

我有这个,但它似乎不必要地麻烦

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:template match="/">
        <xsl:apply-templates select="ol"/>
    </xsl:template>
    
    <xsl:template match="ol">
        <ol>
            <xsl:apply-templates select="li"/>
        </ol>
    </xsl:template>
    
    <xsl:template match="li">
        <li><xsl:apply-templates select="text()" mode="clean-text"/></li>
    </xsl:template>
    
    <xsl:template match="text()" mode="clean-text">
        <xsl:variable name="normal-text" select="normalize-space(.)"/>
        <xsl:choose>
            <xsl:when test="substring($normal-text,string-length($normal-text),1) = '.'"><xsl:value-of select="normalize-space(substring($normal-text,1,string-length($normal-text)-1))"/></xsl:when>
            <xsl:otherwise><xsl:value-of select="$normal-text"/></xsl:otherwise>
        </xsl:choose>
    </xsl:template>
</xsl:stylesheet>

有没有更聪明的方法来实现同样的目标? 顺便说一句,我使用的是 v1.0,因为它可能在 Microsoft 环境中实例化。 但是 v2.0 解决方案也会很有趣

TIA

【问题讨论】:

  • 其实你所拥有的还不错。它的优点是只对空间进行一次标准化。什么是“繁琐”的是所有其他可以被identity transform模板替换的模板。
  • 但是身份转换只会替换 root 和 ol 模板,不是吗?
  • 不,它可以替换除最后一个模板之外的所有模板 - 匹配模式可以是 li/text()(并且不需要模式)。

标签: xslt xslt-1.0 xslt-2.0


【解决方案1】:

在 XSLT 2 或 3 中,您有 replace 函数:

  <xsl:template match="ol/li[ends-with(normalize-space(.), '.')]">
      <xsl:copy>
          <xsl:value-of select="replace(., '\.\s*$', '')"/>
      </xsl:copy>
  </xsl:template>

在 XSLT 1 环境中,您通常可以调用底层平台(例如 Java 或 .NET 或 PHP 或 Python)以使用支持正则表达式(如 \.\s*$)的类似字符串函数来匹配前面的字符串末尾零个或多个空白字符,前面有一个句号。

或者尝试使用纯 XPath 1 字符串函数来完成这一切

  <xsl:template match="ol/li[substring(normalize-space(), string-length(normalize-space())) =  '.']">
      <xsl:copy>
          <xsl:value-of select="substring(normalize-space(), 1, string-length(normalize-space()) - 1)"/>
      </xsl:copy>
  </xsl:template>

在所有情况下,通过身份转换模板处理复制其他内容:https://xsltfiddle.liberty-development.net/jxNakAW

【讨论】:

    猜你喜欢
    • 2019-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-12
    • 2013-10-17
    • 1970-01-01
    • 2014-09-02
    • 1970-01-01
    相关资源
    最近更新 更多