【问题标题】:Remove all single characters from string using xslt1.0使用 xslt1.0 从字符串中删除所有单个字符
【发布时间】:2012-02-01 05:03:23
【问题描述】:
<title>
 <article_title>Land a b   c   d      Band</article_title>
</title>

使用以下函数

replace(article_title, '(^[^ ]+)(.+\s+)([^ ]+)$', '$1 $3')

这个字符串被转换为 Land Band,这正是我想要的。

但问题是我在 xslt 1.0 中需要这个解决方案,因为我正在使用的 java 应用程序只能处理 xslt 1.0 解析。

【问题讨论】:

    标签: xslt-1.0


    【解决方案1】:

    这个 XSLT 1.0 转换(有一个讨厌的 SO 错误并且代码没有缩进 - 我为这个视觉混乱道歉......):

    <xsl:stylesheet version="1.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
     <xsl:output omit-xml-declaration="yes" indent="yes"/>
     <xsl:strip-space elements="*"/>
    
     <xsl:template match="node()|@*">
      <xsl:copy>
       <xsl:apply-templates select="node()|@*"/>
      </xsl:copy>
     </xsl:template>
    
     <xsl:template match="text()" name="removeSingles">
       <xsl:param name="pText" select="."/>
    
       <xsl:variable name="vText" select="normalize-space($pText)"/>
    
       <xsl:if test="string-length($vText)">
        <xsl:variable name="vLeftChars" select=
        "substring-before(concat($vText, ' '), ' ')"/>
    
        <xsl:if test="string-length($vLeftChars) >1">
         <xsl:value-of select="$vLeftChars"/>
         <xsl:if test=
          "not(string-length($vLeftChars)
              >=
               string-length($vText)
               )
          ">
           <xsl:text> </xsl:text>
          </xsl:if>
        </xsl:if>
    
        <xsl:call-template name="removeSingles">
         <xsl:with-param name="pText" select=
         "substring-after($vText, ' ')"/>
        </xsl:call-template>
       </xsl:if>
     </xsl:template>
    </xsl:stylesheet>
    

    应用于提供的 XML 文档时

    <title>
     <article_title>Land a b   c   d      Band</article_title>
    </title>
    

    产生想要的正确结果

    <title>
       <article_title>Land Band</article_title>
    </title>
    

    【讨论】:

    • Dimitre,谢谢,看起来应该可以了,我怎么称呼它?这是正确的
    • @sanjay:“它不起作用”是什么意思。我总是在发布之前测试我的答案。只需在提供的 XML 文档上运行转换,您就应该得到报告的结果。如果不是,那么要么您修改了 XSLT 代码,要么您修改了 XML 文件,或两者兼而有之,或者您的 XSLT 处理器有问题/不完全兼容。
    • Dimitre,我非常感谢您的努力和时间,我必须仅将其应用于我的 xml 中的特定元素。这就是我调用 的方式正确吗?
    • @sanjay:不,你需要:&lt;xsl:call-template name="removeSingles"&gt; &lt;xsl:with-param name="pText" select="yourElement"/&gt;&lt;/xsl:call-template&gt;。另外,从removeSingles xsl:template 指令中删除match="text()"
    • Dimitri,非常感谢......它工作正常。在您之前的评论中,您要求我删除 match="text()" 我该怎么做以及有什么好处?
    猜你喜欢
    • 2011-10-21
    • 1970-01-01
    • 2010-11-04
    • 2010-12-04
    • 1970-01-01
    • 2017-05-09
    • 2015-12-02
    • 2014-09-15
    • 1970-01-01
    相关资源
    最近更新 更多