/// 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"
    <xsl:output indent="yes" encoding="utf-8"/>
    <xsl:template match="/">
        <xsl:apply-templates />

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

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

    <recipe name="0001" prep_time="0002" cook_time="0003">
        <ingredient amount="0005" unit="0006">0007</ingredient>
        <ingredient amount="0008" unit="0009">0010</ingredient>
        <ingredient amount="0011" unit="0012" state="0013">0014</ingredient>

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.


Post a Comment

<< Home

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