python88
python88

Reputation: 3

How can I with XSLT get count of all preceding elements that have specified attribute name?

I have some XML file that contains elements with id attributes. I need to have id values in proper order counting from the root element. So instead of this one:

       <body>
            <p id="1">
                <span id="3"/>
            </p>
            <p/>
            <div id="8">
                <p id="2"/>
                <ul>
                    <li/>
                    <li id="9">
                        <span id="12"/>
                    </li>
                    <li/>
                    <li id="13">
                        <span id="7"/>
                    </li>
                </ul>
            </div>
        </body>

I would like to have this:

        <body>
            <p id="1">
                <span id="2"/>
            </p>
            <p/>
            <div id="3">
                <p id="4"/>
                <ul>
                    <li/>
                    <li id="5">
                        <span id="6"/>
                    </li>
                    <li/>
                    <li id="7">
                        <span id="8"/>
                    </li>
                </ul>
            </div>
        </body>

Upvotes: 0

Views: 37

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167506

Use the identity transformation template plus one for the id attributes:

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="@id">
    <xsl:attribute name="id">
        <xsl:number count="*[@id]" level="any"/>
    </xsl:attribute>
</xsl:template>

http://xsltransform.net/3NSSEvD

Upvotes: 1

Related Questions