Monday, March 11, 2024

OIC - XSLT - Find out the sum of all the invoice lines where each line having quantity and price using Call template

Usecase: we have a source json file where we have multiple items or lines and in each line we have line quantity and price. We have to find out the total amount of all the lines in XSLT.

Source payload:

{
  "gp_number" : "56826526",
  "lineLevel" : [ {
    "Qty" : "4.00",
    "Rate" : "50.00"
  }, {
    "Qty" : "3.00",
    "Rate" : "25.00"
  } ]
}


Target Payload:

{
  "gp_number" : "56826526",
  "AmountCal_line" : [ {
    "Qty" : "4.00",
    "Rate" : "50.00",
    "Amount" : "200.00"
  }, {
    "Qty" : "3.00",
    "Rate" : "25.00",
    "Amount" : "75.00"
  } ],
  "TotalAmount" : "275.00"
}

Xslt sample:

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

  <xsl:output method="text" omit-xml-declaration="yes"/>

  <xsl:template match="/rootElement">
    <!-- Initialize sum variable -->
    <xsl:variable name="totalSum">
      <xsl:call-template name="calculateTotal">
        <xsl:with-param name="items" select="items/item"/>
      </xsl:call-template>
    </xsl:variable>


    <!-- Output the total sum -->
    <xsl:value-of select="$totalSum"/>
  </xsl:template>

  <xsl:template name="calculateTotal">
    <xsl:param name="items"/>
    <xsl:param name="sum" select="0"/>

    <!-- Check if there are more items to process -->
    <xsl:choose>
      <xsl:when test="$items">
        <!-- Calculate quantity multiplied by rate for the current item -->
        <xsl:variable name="itemTotal" select="$sum + $items[1]/qty * $items[1]/rate"/>
       
        <!-- Recursively call the template for the next item -->
        <xsl:call-template name="calculateTotal">
          <xsl:with-param name="items" select="$items[position() > 1]"/>
          <xsl:with-param name="sum" select="$itemTotal"/>
        </xsl:call-template>
      </xsl:when>
      <xsl:otherwise>
        <!-- Return the final sum when all items are processed -->
        <xsl:value-of select="$sum"/>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

</xsl:stylesheet>


Screenshots:








No comments:

Post a Comment

Featured Post

Types of encryption techniques

There are several types of encryption techniques used to secure data, each with its own use case and strengths: 1. Symmetric Encryption Us...