Raghuvir Singh
Raghuvir Singh

Reputation: 85

Generating incremental ID for xml attributes using XSLT

I have following XSL.

    <?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" version="1.0" encoding="UTF-8" indent="yes"/>
        <xsl:template match="/">
            <xsl:element name="root">
                <xsl:apply-templates select="ModelDefinition/ContainerSpecNode"/>
            </xsl:element>
        </xsl:template>
        <xsl:template match="ContainerSpecNode">
            <xsl:element name="item">
                <xsl:attribute name="id"><xsl:value-of select="@specId"/></xsl:attribute>
                <xsl:attribute name="pathId"><xsl:value-of select="@pathId"/></xsl:attribute>
                <xsl:attribute name="specId"><xsl:value-of select="@specId"/></xsl:attribute>
                <xsl:attribute name="rel"><xsl:value-of select="@specType"/></xsl:attribute>
                <xsl:element name="content">
                    <xsl:element name="name">
                        <xsl:value-of select="shortName"/>
                        <xsl:if test="(@minimumCardinalityCount = '0') or (@maximumCardinalityCount != '1')"> [<xsl:value-of select="@minimumCardinalityCount"/>..<xsl:value-of select="@maximumCardinalityCount"/>]</xsl:if>
                    </xsl:element>
                </xsl:element>
                <xsl:apply-templates select="propertySpecs/PropertySpecNode">
                    <xsl:sort select="shortName"/>
                </xsl:apply-templates>
            </xsl:element>
        </xsl:template>
</xsl:stylesheet>

Here I want to create create incremental unique number for ID attributes of Item element for each containerSpecNode just like "Tree_node_1" , "Tree_Node_2" and so on... Here I modified code like this.

. . . . . .
<xsl:element name="item">
<xsl:variable name="count">
            <xsl:number/>
            </xsl:variable>
            <xsl:attribute name="id"><xsl:value-of select="'Tree_Node_'"/><xsl:value-of select="$count+1"/></xsl:attribute>

It increments count value but not for all ContainerSpecNode. Some ID have duplicate value.

I want create for each ContainerSpecNode. How can i do this. Can I use for-each loop? and How?

Upvotes: 0

Views: 1785

Answers (1)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243459

You are close to a correct solution.

Just replace:

<xsl:variable name="count">             
  <xsl:number/>             
</xsl:variable> 

with:

<xsl:variable name="count" select=
     "count(preceding::ContainerSpecNode | ancestor::ContainerSpecNode) +1"/>             

Upvotes: 2

Related Questions