Last Updated: February 25, 2016
· irregularshed

Serializing XML nodes in XSL

Using XSL as a templating engine for projects is something that I'd like to think has disappeared, in favour of things like Twig and Smarty that can do the job a lot better. But sometimes you find yourself having to debug or add features to some existing XSL, and figuring out what's happening with your XML input can be a nightmare, especially when you've got a load of nested templates with parameters going here and there. In the end, you're staring at the screen, head in hands, swearing at your code - and that helps nobody.

What you need to do is serialize a node at a point in your template so you can figure out why you can't get hold of that one f@%!ing value you need. Unlike with modern templating engines, you've got nothing to hand. WELL TRY THIS SOLDIER!

Add the following templates to your stylesheet (or, frankly, any stylesheet you know your environment will pick up):

<xsl:template match="*" mode="serialize">
    <xsl:text>&lt;</xsl:text><xsl:value-of select="name(.)" />
    <xsl:apply-templates mode="serialize" />
    <xsl:text>&lt;/</xsl:text><xsl:value-of select="name(.)" />

<xsl:template match="text()" mode="serialize">
    <xsl:value-of select="." />

Disclosure: I found the basics of this here, formatted it better and, essentially, fixed the < and > which are rendered as < and > on that site

With that done, when you're in the depths of nesting, in a for-each loop or whatever, you can get a handle on things by including:

<xsl:apply-templates select="." mode="serialize" />

Which will output XML. Unformatted, basic XML without parameters, but XML all the same. And hopefully then you'll know where you are!

If you're feeling cheeky you could just dump your node in a textarea. I wasn't aware of this until a scamp told me. CHEEKY!

<textarea><xsl:copy-of select="." /><textarea>

Maybe I should do another protip with this nugget of newly acquired knowledge and clean up on the XSL protip charts...

Say Thanks