【问题标题】:Doing the sum of multiple value做多个值的总和
【发布时间】:2014-07-23 17:00:45
【问题描述】:

想要在 xsl 中添加每个节点的价格值。但这些值也可以有 -9756vc(eg) 类型的值,不需要包含在总和中,然后它给出 NaN 作为我不想要的结果。我无法弄清楚我们如何做到这一点。 以下是示例 XML:

<?xml version="1.0" encoding="UTF-8"?>
<catalog>
    <cd>
        <title>Empire Burlesque</title>
        <artist>Bob Dylan</artist>
        <country>USA</country>
        <company>Columbia</company>
        <price>-9756vc</price>
        <year>1985</year>
    </cd>
    <cd>
        <title>Hide your heart</title>
        <artist>Bonnie Tyler</artist>
        <country>UK</country>
        <company>CBS Records</company>
        <price>9.90</price>
        <year>1988</year>
    </cd>
    <cd>
        <title>Greatest Hits</title>
        <artist>Dolly Parton</artist>
        <country>USA</country>
        <company>RCA</company>
        <price>9.90</price>
        <year>1982</year>
    </cd>
</catalog>

我正在尝试的代码。

     <?xml version="1.0" encoding="ISO-8859-1"?>

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

<xsl:template match="/">
  <html>
  <body>
  <h2>My CD Collection</h2>
    <table border="1">
      <tr bgcolor="#9acd32">
        <th style="text-align:left">Title</th>
        <th style="text-align:left">Artist</th>`enter code here`
      </tr>
      <xsl:for-each select="catalog/cd">
      <tr>
     <xsl:variable name="color" select="format-number(price,'0.##')" /> 
 <xsl:choose>
      <xsl:when test="$color = 'NaN' ">
       <td> <xsl:value-of select="'0'"/> </td>
       </xsl:when>
      <xsl:otherwise>
         <td><xsl:value-of select="$color"/></td>
      </xsl:otherwise>
      </xsl:choose>
        <td><xsl:value-of select="artist"/></td>
      </tr>
      </xsl:for-each>
<xsl:for-each select="catalog/cd">
<xsl:variable name="color" select="format-number(price,'0.##')" /> 
<xsl:choose>
      <xsl:when test="$color != 'NaN' ">
 <xsl:variable name="Sum" select ="$color + 1"/>
<xsl:value-of select="$Sum"/>
</xsl:when>
      </xsl:choose>
      </xsl:for-each>
    </table>
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>

【问题讨论】:

  • 在这种情况下,您是否可以显示您实际期望的输出?谢谢!

标签: xml xslt


【解决方案1】:

值得指出的是,变量在 XSLT 中是不可变的,一旦设置就不能更改。这意味着您不能遍历 xsl:for-eachcd 元素并保持运行总数。

但是,您可以使用 sum 函数,它可以与 xpath 表达式结合使用以仅选择具有数字价格的 cd 元素。如果您前往XPath test if node value is number,您将看到检查节点是否为数字的方法如下:

 number(price) = price

因此,要获得所有有效价格的总和,您可以这样做

<xsl:value-of select="sum(catalog/cd[number(price) = price]/price)" />

这一行将替换 XSLT 中的第二个 xsl:for-each 循环。对于您的 XML,它将返回值 19.8

【讨论】:

    猜你喜欢
    • 2013-05-22
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-15
    • 2021-10-25
    • 1970-01-01
    相关资源
    最近更新 更多