Saxon XSLT2.0从字符串中提取数字

Premkumar

我正在尝试使用Xslt2.0从字符串中提取整数,例如,考虑字符串“ designa80000dd5424d”,并且我需要在字符串中使用两个整数,即“ 8000”和“ 5424”

我尝试使用翻译功能如下

select =“ translate($ term,translate($ term,'0123456789',``),'')''

但是它结合了两个整数,并给出“ 80005424”的输出,我需要将它们分开的东西

迪米特·诺夫切捷夫(Dimitre Novatchev)

我尝试使用翻译功能如下

select =“ translate($ term,translate($ term,'0123456789',``),'')''

但是它结合了两个数字,并输出为“ 80005424”,我需要将它们分开的东西

I.这是完整的XSLT 1.0解决方案

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="text"/>

  <xsl:template match="/*">
    <xsl:variable name="vSpaces">
      <xsl:call-template name="makeSpaces"/>
    </xsl:variable>

    <xsl:variable name="vtheNumbers" 
         select="normalize-space(translate(., translate(.,'0123456789',''), $vSpaces))"/>

    <xsl:call-template name="tokenize">
      <xsl:with-param name="pStr" select="$vtheNumbers"/>
    </xsl:call-template>
  </xsl:template>

  <xsl:template name="tokenize">
    <xsl:param name="pStr"/>
    <xsl:param name="pInd" select="1"/>

    <xsl:if test="string-length($pStr)">
      <xsl:value-of select=
           "concat($pInd, ': ',substring-before(concat($pStr, ' '), ' '), '&#xA;')"/>

      <xsl:call-template name="tokenize">
        <xsl:with-param name="pStr" select="substring-after($pStr, ' ')"/>
        <xsl:with-param name="pInd" select="$pInd +1"/>
      </xsl:call-template>
    </xsl:if>
  </xsl:template>

  <xsl:template name="makeSpaces">
    <xsl:param name="pLen" select="string-length(.)"/>

    <xsl:choose>
      <xsl:when test="$pLen = 1">
        <xsl:value-of select="' '"/>
      </xsl:when>
      <xsl:when test="$pLen > 1">
        <xsl:variable name="vHalfLen" select="floor($pLen div 2)"/>

        <xsl:call-template name="makeSpaces">
          <xsl:with-param name="pLen" select="$vHalfLen"/>
        </xsl:call-template>
        <xsl:call-template name="makeSpaces">
          <xsl:with-param name="pLen" select="$pLen -$vHalfLen"/>
        </xsl:call-template>
      </xsl:when>
    </xsl:choose>
  </xsl:template>
</xsl:stylesheet>

在以下XML文档上应用此转换时

<t>designa80000dd5424dan1733g122</t>

所需的正确结果产生了

1: 80000
2: 5424
3: 1733
4: 122

注意事项

外部函数的最后一个参数translate()是一个字符串,该字符串的字符数与输入字符串的字符数相同,并且每个字符都是一个空格。


二。XPath 2.0更短,更简单

评估时,此XPath 2.0表达式会产生所需的数字序列:

tokenize(., '[^\d]+')[.]

这是基于XSLT的验证

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

  <xsl:template match="/*">
    <xsl:variable name="vNumbers" 
    select="tokenize(., '[^\d]+')[.]"/>

    <xsl:for-each select="$vNumbers">
      <xsl:value-of select="concat(position(), ': ', ., '&#xA;')"/>
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>

当此转换应用于相同的XML文档时

<t>designa80000dd5424dan1733g122</t>

产生相同的正确结果

1: 80000
2: 5424
3: 1733
4: 122

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章