Mega Code Archive

 
Categories / XML / XSLT StyleSheet
 

Define and use template

File: Data.xml  <poem>    <author>author 1</author>    <date>1912</date>    <title>Song</title>   <stanza>       <line>line 1</line>       <line>line 2</line>       <line>line 3</line>       <line>line 4</line>    </stanza>    <stanza>       <line>line 5</line>       <line>line 6</line>       <line>line 7</line>       <line>line 8</line>    </stanza>    <stanza>       <line>line 9</line>       <line>line 10</line>       <line>line 11</line>       <line>line 12</line>    </stanza> </poem> File: Transform.xslt <?xml version="1.0" encoding="iso-8859-1"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"   version="1.0">   <xsl:template match="poem">     <html>       <head>         <title>           <xsl:value-of select="title" />         </title>       </head>       <body>         <xsl:apply-templates select="title" />         <xsl:apply-templates select="author" />         <xsl:apply-templates select="stanza" />         <xsl:apply-templates select="date" />       </body>     </html>   </xsl:template>   <xsl:template match="title">     <div align="center">       <h1>         <xsl:value-of select="." />       </h1>     </div>   </xsl:template>   <xsl:template match="author">     <div align="center">       <h2>         By         <xsl:value-of select="." />       </h2>     </div>   </xsl:template>   <xsl:template match="date">     <p>       <i>         <xsl:value-of select="." />       </i>     </p>   </xsl:template>   <xsl:template match="stanza">     <p>       <xsl:apply-templates select="line" />     </p>   </xsl:template>   <xsl:template match="line">     <xsl:if test="position() mod 2 = 0">&#160;&#160;</xsl:if>     <xsl:value-of select="." />     <br />   </xsl:template> </xsl:stylesheet> Output: <html>    <head>       <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">       <title>Song</title>    </head>    <body>       <div align="center">          <h1>Song</h1>       </div>       <div align="center">          <h2>                     By                     author 1          </h2>       </div>       <p>line 1<br>&nbsp;&nbsp;line 2<br>line 3<br>&nbsp;&nbsp;line 4<br></p>       <p>line 5<br>&nbsp;&nbsp;line 6<br>line 7<br>&nbsp;&nbsp;line 8<br></p>       <p>line 9<br>&nbsp;&nbsp;line 10<br>line 11<br>&nbsp;&nbsp;line 12<br></p>       <p><i>1912</i></p>    </body> </html>