xml – XSLT transformation adding attributes to the root element

Question:

<stock>
    <product description=”product1” quantity="11" price=”3.90” />
    <product description=”product2” quantity="33"  price=”9.50” />
    <product description=”product3” quantity="22"  price=”6.10” />
</stock>

How to make an XSLT transformation that adds the following attributes to the root element:

totalpositions – общее количество строк в заказе
totalquantity – суммарное количество заказанных изделий
totalsum – общая стоимость заказа

Answer:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="stock">
    <xsl:copy>

      <xsl:attribute name="totalpositions">
        <xsl:value-of select="count(product)" />
      </xsl:attribute>
      <xsl:attribute name="totalquantity">
        <xsl:value-of select="sum(product/@quantity)" />
      </xsl:attribute>
      <xsl:attribute name="totalsum">
        <xsl:value-of select="sum(product/@price)" />
      </xsl:attribute>

      <xsl:copy-of select="product" />
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>
Scroll to Top