Home > Mobile >  XSLT: How to count the total number of a specific element under a root element
XSLT: How to count the total number of a specific element under a root element

Time:10-05

I would like to count a specific element. How can I do that?

For example, I'm counting app element

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="sum.xsl"?>

<sum>      
  <!-- expect Two -->
  <ab1 param="a">
    <ab2 param="b">
      <app> <!--  1 -->
        <var1 name="a"/>
        <app> <!--  1 -->
          <var2 name="a"/>
        </app>
      </app>
    </ab2>
  </ab1>
</sum>

I expect the output like this

<?xml version="1.0" encoding="UTF-8"?>
2

CodePudding user response:

You could so:

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

<xsl:template match="/sum">
    <xsl:for-each select="abstraction">
        <xsl:value-of select="count(.//application)" />
        <xsl:text>&#10;</xsl:text>
    </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

CodePudding user response:

You don't say what version of XSLT you need, so I just wrote this in XSLT 1.0.

NB I used <xsl:output method="text"/> to produce a plain text file. Hence there's no XML declaration as in your desired output, which would be misleading since the output is not in fact XML.

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

  <xsl:output method="text"/>
  
  <xsl:template match="/*">
    <xsl:for-each select="*">
      <xsl:value-of select="count(.//application)"/>
      <xsl:text>&#xa;</xsl:text>
    </xsl:for-each>
  </xsl:template>
  
</xsl:stylesheet>

  •  Tags:  
  • html
  • Related