XSLT Explained

What is XSLT?

XSLT is, in my opinion, similar to the likes of the Mako and Chameleon templating engines. XSLT is mainly used to transform some type of structured markup language (like XML) to another form, like HTML, JSON, or even another XML document. This is done through the use of XPath identifiers and XSL tag elements. For a transformation of one XML document to another, you might use an XSLT template element, which uses an existing XSLT file to define how the resulting XML should look.

Why is XSLT Useful?

The usefulness of XSLT can best be shown by example. So lets say we have the XML document below:

<?xml version="1.0" encoding="ISO-8859-1"?>

Maybe we'd rather display parts of this XML in a nice, human readable format, like HTML. So we'd then create a template, like this:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
      <h5>My Car Collection</h5>
      <table border="1">
        <tr bgcolor="#EC5923">
          <td><xsl:value-of select="collection/car/make"/></td>
          <td><xsl:value-of select="collection/car/model"/></td>

Using this template on the XML we had above would result in the following HTML:

My Car Collection
Make Model
Lamborghini Gallardo

This, obviously, is much easier to read. Although, XSLT doesn't strickly need to be used to transform XML in to HTML. Instead you could use it to just transform XML in to a different structure.

For another example, maybe you work for a company that receives XML data from it's suppliers that details how much inventory they have available for their products, A through Z. But you only care about products S, R, and W, so instead of storing all of that unnecessary information you would instead use an XSLT template to extract out only the information you care about, which in this case is products S, R, and W. Applying this method in a larger scale would result in a lot of saved memory and much less clutter to deal with. Plus, changing the document format would arguably be much easier than having to recompile code that does the same thing.

Keep in mind that this short example only shows a small amount of what XSLT can actually do. To get a better idea of what's possible, be sure to check out the resources below.

How do you use XSLT?

There are many ways of using XSLT, including browsers, Java, Python, and pretty much any other programming language you can think of.

As with everything, XSLT transforms can easily be done in Python (with the lxml package):

import lxml.etree as et

xml = et.parse(xml_filename)
xslt = et.parse(xsl_filename)
transform = et.XSLT(xslt)
newXml = transform(xml)
print(et.tostring(newXml, pretty_print=True))

And as I mentioned before, XSLT can easily transform XML to JSON.