Dissection of the pole.xml Example
Before we try the pole.xml example, let's dissect it, bit by bit.
<xsl:template match="/"> <HTML> <BODY> <xsl:apply-templates/> </BODY> </HTML> </xsl:template>
This is the template rule for the root element of the source document. It states that all the child elements will be processed according to the template rules defined for them, either explicitly or implicitly. Notice that this rule does not stipulate the order in which the child elements are processed. There are three children under the top-level element: one <title>
element and two <section>
elements. They will be processed in the order in which they appear in the source document.
The complexity of the <section>
elements is similar to that of the root element. Each contains various child elements without any apparent order. Therefore, the elements can be processed in a similar way:
<xsl:template match="section"> <DIV> <xsl:apply-templates /> </DIV> </xsl:template>
Because a <section>
element can contain other <section>
elements recursively, the above template rule will be applied recursively.
The <title>
element appears as a child element of both <document>
and <section>
. If you want all the titles to appear in the same way, use a template rule similar to following:
<xsl:template match="title"> <H1><xsl:value-of select="text()"/></H1> </xsl:template>
Here we have assumed that the <title>
element is a text node. If <title>
contains other elements as well, we need to modify the above template so it can handle either case:
<xsl:template match="title"> <H1><xsl:apply-templates /></H1> </xsl:template>
This will work even if <title>
is still a text node, and you do not explicitly define a template rule for a text node. The default template rule for a text node will be called instead.
The template-rule above matches any <title>
found in the source document. However, you might want to distinguish the document title from the section titles. To do this, we need two template rules:
<xsl:template match="document/title">
<H1><xsl:apply-templates /></H1>
</xsl:template>
<xsl:template match="section/title">
<H2><xsl:apply-templates /></H2>
</xsl:template>
To complete the transformation of the source document, we also need the following template rules for the remaining elements:
<xsl:template match="p"> <P><xsl:apply-templates /></P> </xsl:template> <xsl:template match="list"> <UL> <xsl:for-each select="item"> <LI><xsl:apply-templates /></LI> </xsl:for-each> </UL> </xsl:template> <xsl:template match="emph"> <I><xsl:apply-templates /></I> </xsl:template>
Finally, we need an explicit definition of the template rule for a text node:
<xsl:template match="text()"> <xsl:value-of select='.' /> </xsl:template>
The following topics provide more information about handling irregular data hierarchies.
- Combining Data-Driven and Template-Driven Transformations
- Example of Transforming Irregular Data Hierarchies