Thursday, September 12, 2013

A Small XSLTip

While making some minor changes to my website recently, I encountered an interesting problem - that of displaying a URL on an XML-XSLT web page. But before I get into the problem and the solution, time for some introductions for the benefit of newbies...

XML: Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. It is a textual data format with strong Unicode support (more on Wikipedia)

XSLT: Extensible Stylesheet Language Transformations (XSLT ) is a language for transforming XML documents into other XML documents, or other objects such as HTML, plain text or XSL Formatting Objects for processing into other formats (more on Wikipedia)

My XML code was as follows:

 <lines>
  <line name="Company" linetext="Capgemini Consulting India Pvt. Ltd." />
  <line name="Description" linetext="Capgemini is a global leader in consulting, technology, outsourcing and local professional services. It employs more than 83,000 employees globally." />
  <line name="My tenure" linetext="2004-2012" />
  <line name="My role" linetext="Manager" />
  <line name="Comments" linetext="Cap was my first big break and the career growth I got was phenomenal. Indeed, the Capgemini stint totally changed me at a personal level." />
  <line name="Website" linetext="http://in.capgemini.com" />
 </lines>

The challenge was to ensure that the website name appeared as a valid URL, whereas the other lines appeared as plain text. This meant that the highlighted "line" with the "name" of "Website" had to be processed in a different way from all the other "lines". After some web searching, I came up with the following XSLT code for processing the "line" tags:

 <xsl:template match="line">
  <tr>
   <td width="30%" align="right" valign="middle" class="itemtext">
    <b><xsl:value-of select="@name" />:</b>
   </td>
   <td width="70%" align="left" valign="middle" class="itemtext">
    <xsl:if test="@name='Website'">
     <a href="{@linetext}"> 
      <xsl:value-of select="@linetext"/>
     </a>
    </xsl:if>
    <xsl:if test="@name!='Website'">
     <xsl:value-of select="@linetext" />
    </xsl:if>
   </td>
  </tr>
  <tr>
   <td colspan="2" align="center" valign="middle">&#160;</td>
  </tr>
 </xsl:template>

Hopefully the above XSLT code is self-explanatory. If not, feel free to contact me for a discussion

No comments:

Post a Comment