Krishna Rajendra Alapati

IT Professional having 4+ years of experience on Java and JEE technologies. Good experience in working with Servlets, JSP, EJB2, XML, XSLT and JEE Design patterns. Good experience in working with open source frameworks like Struts, Spring, Hibernate, ANT, JUnit and JMock.

My Photo
Name:
Location: London, Ilford, United Kingdom

Monday, November 21, 2005

Getting the Table of contents for a xml using xsl

Here is a typical example to create a Table of Contents for a given particular xml


XML:


<?xml version="1.0" encoding="UTF-8"?>

<main title="Main Heading">
<section title="Heading1">
<section title="Heading1.1" >
<section title="Heading1.1.1"></section>
<section title="Heading1.1.2"></section>
</section>
<section title="Heading2" >
<section title="Heading2.1"></section>
<section title="Heading2.2"></section>
</section>
</section>
</main>

Output:

Main Heading
1)Heading1
1.1)Heading1.1
1.1.1)Heading1.1.1
1.1.1)Heading1.1.2
2)Heading2
2.1)Heading2.1
2.2)Heading2.2


Answer is here

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" />

<xsl:template match="/main">
<xsl:value-of select="@title"/>
<xsl:text>
</xsl:text>
<xsl:call-template name="p">
<xsl:with-param name="prefix" select="''" />
<xsl:with-param name="indent" select="' '" />
</xsl:call-template>
</xsl:template>

<xsl:template name="p" >
<xsl:param name="prefix" />
<xsl:param name="indent" />
<xsl:for-each select="section" >
<xsl:value-of select="$indent"/>
<xsl:value-of select="$prefix"/>
<xsl:value-of select="position()"/>) <xsl:value-of select="@title" />
<xsl:text>
</xsl:text>
<xsl:call-template name="p">
<xsl:with-param name="prefix" select="concat($prefix, position(), '.')" />
<xsl:with-param name="indent" select="concat($indent, ' ')" />
</xsl:call-template>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>

0 Comments:

Post a Comment

<< Home