Search code examples
xmlxsltxslt-1.0xslt-2.0

Excluding certain values from an xsl:sum equation


Within my stylesheet, I have an xsl:variable that looks into the XML, looks at a list of objects and returns the sum of the price value from each object, my code for that is exampled below:

  <xsl:variable name="ExampleTotal">
      <xsl:value-of select="sum(/ListOfObjects/Object/PriceOfObject)"/>
  </xsl:variable>

And this works fine, My problem is that I don't need the sum of every one of these objects in the list, only the ones that contain a value of being true.

Example XML:

<ListOfObjects>
  <Object>
    <PriceOfObject>35.00</PriceOfObject>
    <PriceNeeded>true</PriceNeeded>
    <OtherData>example</OtherData>
  </Object>
  <Object>
    <PriceOfObject>36.00</PriceOfObject>
    <PriceNeeded>true</PriceNeeded>
    <OtherData>example</OtherData>
  </Object>
  <Object>
    <PriceOfObject>35.00</PriceOfObject>
    <PriceNeeded>true</PriceNeeded>
    <OtherData>example</OtherData>
  </Object>
  <Object>
    <PriceOfObject>33.00</PriceOfObject>
    <PriceNeeded>false</PriceNeeded>
    <OtherData>example</OtherData>
 </Object>
</ListOfObjects>   

is it possible to look through the list of objects and only sum up the total of the ones that have the value as true?


Solution

  • Try this:

    <xsl:variable name="ExampleTotal">
      <xsl:value-of select="sum(/ListOfObjects/Object[PriceNeeded='true']/PriceOfObject)"/>
    </xsl:variable>
    

    Above code changed as suggested by Michael Kay,

    <xsl:variable name="ExampleTotal" 
      select="sum(/ListOfO‌​bjects/Object[PriceNe‌​eded='true']/PriceOfO‌​bject)"/>