medasuresh
medasuresh

Reputation: 11

How to get the occurrence of a tag in XSLT with its count increment over its occurrence

I have an XML like this:

<?xml version="1.0" encoding="utf-8"?>
<lines>
    <accounts>
        <account>
            <p lang="en">
                <trans> SAVINGS.</trans>
            </p>
        </account>
        <account>
            <p lang="en">
                <trans> CREDIT</trans>
            </p>
        </account>
    </accounts>
    <deposits>
        <account>
            <p lang="en">
                <trans> SAVINGS DEPOSIT.</trans>
            </p>
        </account>
        <account>
            <p lang="en">
                <trans> CREDIT DEPOSIT</trans>
            </p>
        </account>
    </deposits>
</lines>

But I want to print as below in XSLT:

Account 1) SAVINGS
Account 2) CREDIT
Account 3) SAVINGS DEPOSIT
Account 4) CREDIT DEPOSIT<

what XSLT expression will be best for this?

I tried with below XSLT

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="trans" >
        <xsl:if test="ancestor::account">
           Account <xsl:number value="count(account)" format="1"/>
        </xsl:if>
        <xsl:apply-templates/>
    </xsl:template>
</xsl:stylesheet>

But I get the output as

Account 0 SAVINGS
Account 0 CREDIT   
Account 0 SAVINGS DEPOSIT             
Account 0 CREDIT DEPOSIT

what would be the best expression to resolve this..?

Upvotes: 1

Views: 46

Answers (2)

michael.hor257k
michael.hor257k

Reputation: 116959

I would do:

XSLT 1.0

<xsl:stylesheet version="2.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>

<xsl:template match="/lines">
    <xsl:for-each select="*/account">
        <xsl:text>Account </xsl:text>
        <xsl:number value="position()" format="1)"/>
        <xsl:value-of select="p/trans"/>        
        <xsl:text>&#10;</xsl:text>
    </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

Upvotes: 0

Martin Honnen
Martin Honnen

Reputation: 167426

Try

<xsl:template match="account//trans">
Account <xsl:number level="any" format="1)"/> <xsl:value-of select="."/>
</xsl:template>

https://xsltfiddle.liberty-development.net/bFWRApb

Upvotes: 1

Related Questions