Natacha BK
Natacha BK

Reputation: 137

XSLT : Sum based on attributes values

I have this document I want to transform to a HTLM doc, using XSLT. I want to sum up the prices by city, meaning I would have the following output :

Chicago 89
New York 144
Washington 147 
Philadeplhia 73

XML Input

<?xml version="1.0" encoding="ISO-8859-1" ?>
<?xml-stylesheet href="class.xsl" type="text/xsl" ?>
<root>
<person><name>John</name>
<property city="Chicago" price="89" />
<property city="New York" price="69" />
<property city="Washington" price="75" /></person>
<person><name>Mike</name>
<property city="New York" price="75" />
<property city="Washington" price="72" />
<property city="Philadeplhia" price="73" /></person>
</root>

I thought that I could use generate.id to generate an unique ID for each city and then a sum(), but it doesn't work :

<xsl:value-of select="root/person/property/@city" /> 
<xsl:value-of select="generate-id(.)" />)

Upvotes: 0

Views: 89

Answers (2)

Natacha BK
Natacha BK

Reputation: 137

Problem solved ! :

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text"/>
  <xsl:strip-space elements="*"/>

  <xsl:key name="property_by_city" match="property" use="@city"/>

  <xsl:template match="/">
    <xsl:for-each select="//property[count(.|key('property_by_city',@city)[1])=1]">
      <xsl:value-of select="concat(@city,' ',sum(key('property_by_city',@city)/@price),'&#xA;')"/>
    </xsl:for-each>
  </xsl:template>
  
</xsl:stylesheet>

Upvotes: 1

barbwire
barbwire

Reputation: 218

maybe this helps you to finding the solution (XSLT 2.0):

<xsl:for-each-group select="//property" group-by="@city">
     <xsl:value-of select="sum(current-group()/@price)"/>
</xsl:for-each-group>

Upvotes: 2

Related Questions