/// Saturday, April 15

XSLT: How to autonumber all elements and attributes.

I'm doing more XSLT transformations and there's a lot of mapping to be done. I want to automate as much of the testing as I can. The first thing in order is how do I easily create a control sample so I can automate all attributes and fields mapped? Another stylsheet of course.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:fo="http://www.w3.org/1999/XSL/Format">
    
    <xsl:output indent="yes" encoding="utf-8"/>
    <xsl:template match="/">
        <xsl:apply-templates />
    </xsl:template>

    <xsl:template match="text()">
        <xsl:number level="any" format="0001" count="text()|@*"/>
    </xsl:template>
    
    <xsl:template match="@*">
        <xsl:attribute name="{name()}">
            <xsl:number level="any" format="0001" count="text()|@*"/>
        </xsl:attribute>
        
    </xsl:template>
        
    <xsl:template match="*">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

This simple stylesheet replaces the value of all attributes and elements with a sequential number from 0001 to n. The result looks like this.

<recipes>
    <recipe name="0001" prep_time="0002" cook_time="0003">
        <title>0004</title>
        <ingredient amount="0005" unit="0006">0007</ingredient>
        <ingredient amount="0008" unit="0009">0010</ingredient>
        <ingredient amount="0011" unit="0012" state="0013">0014</ingredient>
        <instructions>
            <step>0015</step>
            <step>0016</step>
            <step>0017</step>
        </instructions>
    </recipe>
</recipes>

This line needs a little explanation.

<xsl:number level="any" format="0001" count="text()|@*"/>

It says, create a counter for element text (text()) or attribute value (@*) encountered at any level, then format the number returning a four-digit number with leading zeros. The rest of the stylesheet is a modified identity template.

Comments:

Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?