替代数字的总和 (XML/XSL) [英] sum of alternate numbers (XML/XSL)

查看:24
本文介绍了替代数字的总和 (XML/XSL)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要在使用 XSLT 从 XML 文件接收的数字中添加替代数字,例如如果我收到 123456789,我需要使用 XSLT 函数从最右边计算替代数字总和,我可以对此有什么建议吗?

Need to add alternate digits in a number receiving from XML file using XSLT, for instance If I am receiving a 123456789, I need to calculate alternate digit sum from right most using XSLT function, can i have any suggestions on this ?

谢谢,Laxmikanth.S

Thanks, Laxmikanth.S

推荐答案

使用 XSLT 2.0(实际上只是使用单个 XPath 2.0 表达式)非常容易做到这一点:

以下 XSLT 转换:

The following XSLT transformation:

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

    <xsl:template match="/">
      <xsl:sequence select=
      "sum(for $n in reverse(string-to-codepoints('123456789'))
                                     [position() mod 2 eq 1]
             return
               $n  - string-to-codepoints('0') 
           )
      "/>
    </xsl:template>
</xsl:stylesheet>

应用于任何 XML 文档(未使用)时,产生正确的结果:

when aplied on any XML document (not used), produces the correct result:

25

注意 XPath 2.0 函数的使用:string-to-codepoints(), codepoints-to-string()reverse().

Do note the use of the XPath 2.0 functions: string-to-codepoints(), codepoints-to-string() and reverse().

更新:一个类似但更简单的表达是:

UPDATE: A similar, but a little simpler expression is:

sum(for $n in reverse(string-to-codepoints('123456789'))
                                 [position() mod 2 eq 1]
      return
         xs:integer(codepoints-to-string($n))
    )

为了编译这个表达式,xs 前缀必须绑定到命名空间:"http://www.w3.org/2001/XMLSchema"

In order for this expression to compile, the xs prefix must be bound to the namespace: "http://www.w3.org/2001/XMLSchema"

这篇关于替代数字的总和 (XML/XSL)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆