如何得到2个属性相减的结果

How to get the result of the substraction of 2 attributes

考虑这个简单的问题 xml

<books>
  <book>
    <price ht="100" ttc="120"/>
  </book>
  <book>
    <price ht="150" ttc="180"/>
  </book>
</books>

我想为所有 book/price 节点 (ttc - ht)

列出 ttcht 的减法

我知道如何获取 ttc: //book[price]/price/@ttc 和 ht 同样的方法。

如何获取ttc-ht的结果?

要检索每个 book 元素的差异,您可以将此 XSL 代码与 Identity 模板:

结合使用
<xsl:template match="book">
    <xsl:copy>
        <xsl:value-of select="price/@ttc - price/@ht" />
    </xsl:copy>
</xsl:template>

它发出每个 <book> 元素的差异。


要获得所有 <book> 元素属性的总差异,可以使用以下 XPath-1.0 表达式:

<xsl:template match="books">
    <xsl:copy>
        <xsl:value-of select="sum(.//book/price/@ttc) - sum(.//book/price/@ht)" />
    </xsl:copy>
</xsl:template>  

核心的XPath-1.0表达式是,从<books>层开始,这个:

sum(.//book/price/@ttc) - sum(.//book/price/@ht)

此表达式从所有 @ttc 属性中减去所有 @ht 属性。 .// 运算符意味着选择从当前轴开始的所有后代元素。在上面的 XSLT 代码中,current axis<books>.

所以在上面的例子中,结果是50.

尝试

//book/price/(./@ttc - ./@ht)

给定您的样本 xml,输出为:

20
30