tags:

views:

81

answers:

2

I have the following xml:

<RowSet>
  <Row>
    <Number>12345</Number>
    <Quantity>42</Quantity>
  </Row>
  <Row>
    <Number>12345</Number>
    <Quantity>12</Quantity>
  </Row>
  <Row>
    <Number>54321</Number>
    <Quantity>37</Quantity>
  </Row>
</RowSet>

I want to use an xsl to combine the elements with the same Number and the resulting should sum the Quantity elements. So the output should look like this:

<RowSet>
  <Row>
    <Number>12345</Number>
    <Quantity>64</Quantity>
  </Row>
  <Row>
    <Number>54321</Number>
    <Quantity>37</Quantity>
  </Row>
</RowSet>
+1  A: 

These articles describe grouping and summing in XSLT.

mdma
+3  A: 
<xsl:key name="kRow" match="Row" use="Number" />

<xsl:template match="RowSet">
  <xsl:copy>
    <xsl:apply-templates select="Row[
      generate-id() = generate-id(key('kRow', Number)[1])
    ]" />
  </xsl:copy>
</xsl:template>

<xsl:template match="Row">
  <xsl:copy>
    <xsl:copy-of select="Number" />
    <Quantity>
      <xsl:value-of select="sum(key('kRow', Number)/Quantity)" />
    </Quantity>
  </xsl:copy>
</xsl:template>
Tomalak
This is close but the RowSet was removed and I ended up with two Number elements that were identical. Here's the resulting XML:<?xml version="1.0" encoding="UTF-8"?><Row> <Number>20000689</Number> <Quantity>28132</Quantity></Row><Row> <Number>20000689</Number> <Quantity>28132</Quantity></Row><Row> <Number>10000294</Number> <Quantity>1502.778</Quantity></Row>
mpenrow
@mpenrow: Very probably because you are making a mistake. My code is fine, according to your sample.
Tomalak
@Tomalak: Thanks for checking. I am a noob at this xsl stuff so it is entirely possible I am making a mistake.
mpenrow
@mpenrow: Check XML Namespaces, compare case (XML is case sensitive), and also structural differences. You can't be very far.
Tomalak