Wednesday, May 20, 2015

XSLT Learnings

Just listing some XSLT learnings from a recent project where I had to learn from scratch.

Basic shelling:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet xmlns:xsl="" version="2.0">
<xsl:output method="xml" encoding="utf-8" indent="no"/> 
<xsl:template match="/">
    <!-- XSL stuff -->

Converting a list of states from XML to HTML select input options:

Given an input like this:


Use XSL like this:

<select name="states">
    <xsl:for-each select="states/*">
             <xsl:attribute name="value"><xsl:value-of select="name(.)"/></xsl:attribute>
        <xsl:value-of select="string(.)"/>

To get this:

        <option value="AL">Alabama</option>
        <option value="AK">Alaska</option>
        <option value="AR">Arkansas</option>
        <option value="CA">California</option>
        <option value="CO">Colorado</option>

Some few things to note:

  • "name(.)" gives you the element (tag) name.
  • "string(.)" gives you the element value (what is between opening and closong tags).

Checking element has children or content

<xsl:if test="some/element-tag/text() != ''">

No comments:

Post a Comment