Multiple Representations Using Mode for XSLT Templates

dc783f56facdbf2e7f5219af438a188d

When transforming an XML document into another format, XSLT provides a clean and portable method to accomplish the translation, and simple template match rules will often suffice to map the source tree onto the result tree. Often, however, some nodes need to be processed twice and represented more than once in the result tree. The mode attribute of the <xsl:template> tag allows you to selectively apply which XSLT template node you want to a set of nodes.

If the XML represented a web page and the transformation called for a table of contents of all the section headings, using a unique mode value will achieve styling the same section heading nodes in two different ways. When the mode is not specified, the <xsl:template> applies to the matched nodes when applied without a mode specified. This is the default behavior. By creating an <xsl:template mode="toc"> and calling it with the selected nodes with <xsl:apply-templates mode="toc">, you can apply the table of content structure. And then, with a default template rule for styling the section heading nodes, when the parser reaches them in normal document order it will apply the default template rules with mode not set.

Manipulating XML into different structures and doctypes is made possible by XSLT, but performing more than one transformation on a set of nodes is not immediately obvious. The mode attribute of the <xsl:template> and corresponding <xsl:apply-templates> tags can separate different template styles for the same set of nodes within the same result document. It can free up a lot of conditional statements in the templates and make the template designing process easier.

About the Author:
Taylor is a Staff Writer for DevWebPro