Home > Blockchain >  How can I create a new variable with the sum of all elements in the file with XSLT?
How can I create a new variable with the sum of all elements in the file with XSLT?

Time:07-29

I am trying to create a new variable with the total amount of elements ingredient in the file. So what I have:

<?xml version="1.0" encoding="UTF-8"?>
    <pc:recipe
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        version="0.1">
    <pc:ingredient name="tomato">
    </pc:ingredient>
    <pc:ingredient name="onion">
    <pc:ingredient>
    <pc:ingredient name="paprika">
    </pc:ingredient>
   </pc:recipe>

So what I need to create a new variable in the XSLT-file with the total number of ingredients in the XML-file (in this example totalAmount=3):

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema">

Maybe someone can help me with this.

CodePudding user response:

It's simply

<xsl:variable name="number-of-ingredients"
              select="count(//pc:ingredient)"/>

but you'll need to ensure that the prefix "pc" is declared in both the source document and the stylesheet.

CodePudding user response:

Lets assume this is your xml (using a namespace for pc)

<?xml version="1.0" encoding="UTF-8"?>
<pc:recipe version="0.1"
  xmlns:pc="some-url-for-pc" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <pc:ingredient name="tomato"> </pc:ingredient>
  <pc:ingredient name="onion"> </pc:ingredient>
  <pc:ingredient name="paprika"> </pc:ingredient>
</pc:recipe>

And this the xslt:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet 
  version="1.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:pc="some-url-for-pc">
  
  <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
  
  <!--  The identity template -->
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="pc:recipe">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
      <!-- Insert a new element with the number-of-ingredients -->
      <pc:number-of-ingredients>
        <xsl:value-of select="count(pc:ingredient)"/>
      </pc:number-of-ingredients>
    </xsl:copy>
  </xsl:template>  

</xsl:stylesheet>

Than this is the result:

<?xml version="1.0" encoding="UTF-8"?>
<pc:recipe xmlns:pc="some-url-for-pc"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           version="0.1">
   <pc:ingredient name="tomato"> </pc:ingredient>
   <pc:ingredient name="onion"> </pc:ingredient>
   <pc:ingredient name="paprika"> </pc:ingredient>
   <pc:number-of-ingredients>3</pc:number-of-ingredients>
</pc:recipe>
  • Related