Pages

Friday, July 27, 2012

Create reusable counters for consistency

When developing XSL Stylesheets, you may often need to output a formatted number.
With more complex output structures, you may need to maintain links between objects using the same counters. We suggest you create reusable templates to maintain consistency and ensure accurate output.

<?xml version="1.0"?>
<Certification>
    <Exam>
       <Item>
            <Question>Should I use XML?</Question>
            <Answer>Duh.</Answer>
       </Item>
       <Item>
            <Question>Should I use XSL?</Question>
            <Answer>Of course.</Answer>
       </Item>
    </Exam>
</Certification>

If you apply the stylesheet below:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
       <xsl:text>Test:</xsl:text>
       <xsl:apply-templates select="descendant::Question"/>

       <xsl:text> Answer Key:</xsl:text>
       <xsl:apply-templates select="descendant::Answer"/>
    </xsl:template>

    <xsl:template match="*">
       <xsl:apply-templates/>
    </xsl:template>

    <!-- reuseable counter -->
    <xsl:template name="ItemCounter">
       <xsl:number count="Item" from="Exam" format="a"/>
    </xsl:template>

    <xsl:template match="Question | Answer">
       <xsl:text> </xsl:text>
       <xsl:call-template name="ItemCounter"/>
       <xsl:text>.) </xsl:text>
       <xsl:apply-templates/>
    </xsl:template>
</xsl:stylesheet>

It produces the output

Test:
a.    Should I use XML?
b.    Should I use XSL?
Answer Key:
a.    Duh.
b.    Of course.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.