xslt Tutorial : Just Enough xslt to perform...

xslt is a complex language that is used to translate an xml document into anything else.

It is very powerful, yet can be odd to read for the uninitiated.
I cut my teeth on xslt when working on a project that used complex xlst transforms that I had to work out.
Eventually it becomes readable - but I will try to stick to the simple stuff.

This article is intended to become a basic primer.

To start with an xslt template needs the following goo at the start:

<!--?xml version="1.0" encoding="utf-8"?-->
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:PerfectStorm="urn:PerfectStorm">
<xsl:output method="text" standalone="yes" />
<xsl:preserve-space elements="*" />
<xsl:template match="/">

and the following goo at the end

</xsl:template>
</xsl:stylesheet>

This is the basic version of an xslt template - it can get far more involved.

There are several styles of xslt template:

One fills in a document based upon data supplied by an external xml document - this is typically the form that I use for codegen.
Others take an xml document and alter it's values following the structure of the document. This is harder to follow and I have yet to require it for codegen.
However it is there if needed.

Lets give a worked example of the first kind. Note this is not the trivial fill in the blanks option this does a lookup via xpath:

Here is the source document (what I call a model):

<model>
<data id="foo">42</data>
<entity name="Owner" id="foo">
</entity>
</model>

Here is the transform:

<!--?xml version="1.0" encoding="utf-8"?-->
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:PerfectStorm="urn:PerfectStorm">
<xsl:output method="text" standalone="yes" />
<xsl:preserve-space elements="*" />
<xsl:template match="/">
<xsl:for-each select="model/entity">
public class <xsl:value-of select="@name" /> {
//<xsl:value-of select="//data[@id=current()/@id]" />
}
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>

This reads as loop through the model looking for entities (this is the xsl:for-each)
If you find an entity write out some text (the class bit).

Inside the class add a comment that is looked up from the data element with a matching id attribute.
The // in the xpath expression means find me the first item that satisfies the criteria from the top of the document.
It is a useful shorthand.

The bits inside the "" is a restriction clause. The current() refers to the node that we are currently looking at in the xsl:for-each loop.
Tests come in two flavors. This is an equality test. The other form is an xpath expression - in that case if the xpath expression finds a node then it is true, otherwise it is false.

Coming soon ... calling templates and passing parameters.

Last edited Aug 3, 2008 at 8:57 PM by chriseyre2000, version 1

Comments

No comments yet.