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="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="xml" encoding="utf-8" indent="no"/> 
<xsl:template match="/">
    <!-- XSL stuff -->
</xsl:template>
</xsl:stylesheet>

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

Given an input like this:

<states>
    <AL>Alabama</AL>
    <AK>Alaska</AK>
    <AR>Arkansas</AR>
    <CA>California</CA>
    <CO>Colorado</CO>
</states>

Use XSL like this:

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

To get this:

<select>
        <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>
</select>

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() != ''">
...
</xsl:if>

No comments:

Post a Comment