Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using position() function in xslt

Tags:

People also ask

What is position in XML?

Position() function is a recommended operation to return the node position that is being processed. If the position=1, the first element in the XML file returns a position of 1. Similarly, it varies for the number.

What is number () in XSLT?

Definition and Usage. The <xsl:number> element is used to determine the integer position of the current node in the source. It is also used to format a number.

What is current () XSLT?

XSLT current() Function The current() function returns a node-set that contains only the current node. Usually the current node and the context node are the same.

What is text () in XSLT?

XSLT <xsl:text> The <xsl:text> element is used to write literal text to the output. Tip: This element may contain literal text, entity references, and #PCDATA.


<EmployeeDetails>
    <Employee>
        <Name>TEST</Name>
    </Employee>
    <Employee>
        <Name>TEST</Name>
    </Employee>
    <Employee>
        <Name>TEST</Name>
    </Employee>
    <Employee>
        <Name>TEST</Name>
    </Employee>
    <Employee>
        <Name>TEST</Name>
    </Employee>
</EmployeeDetails>

I tried using xslt as below :

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xd="http://www.oxygenxml.com/ns/doc/xsl"
    exclude-result-prefixes="xd"
    version="1.0">

    <xsl:template match="EmployeeDetails/Employee">
        <xsl:copy>
        <xsl:attribute name="id"><xsl:value-of select="position()"/></xsl:attribute>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="*">
        <xsl:element name="{local-name()}">
            <xsl:apply-templates select="@*|node()"/>
        </xsl:element>
    </xsl:template>
    <xsl:template match="@*">
        <xsl:attribute name="{local-name()}">
            <xsl:value-of select="."/>
        </xsl:attribute>
    </xsl:template>
</xsl:stylesheet>

For above xslt the output for position() is printing as 2,4,6,8,10.

and the output should be :

<EmployeeDetails>
    <Employee id="1">
        <Name>TEST</Name>
    </Employee>
    <Employee id="2">
        <Name>TEST</Name>
    </Employee>
    <Employee id="3">
        <Name>TEST</Name>
    </Employee>
    <Employee id="4">
        <Name>TEST</Name>
    </Employee>
    <Employee id="5">
        <Name>TEST</Name>
    </Employee>
</EmployeeDetails>

How to print as a sequence like 1,2,3.... for id attribute.