blog.humaneguitarist.org

layer cake: XML config files with XSL inside CDATA

[Sat, 12 Nov 2011 17:18:51 +0000]
Sometimes in life - or coding projects - there are regrets. But there is cake, too. IMAGE: "yummy looking layer cake"[http://www.wilton.com/img/spumoni-layer-cake-main.jpg] Anyway, for a current project I want to place some XSL inside an XML config file. But of course, you can't just drop XML inside XML without coating it in something. So for another project, PubMed2XL [http://blog.humaneguitarist.org/projects/pubmed2xl/], I did something like this: <cell>{{?xml version="1.0" encoding="UTF-8"?}} {{xsl:stylesheet version="1.0" encoding="UTF-8" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"}} {{xsl:output method = "text" /}} {{xsl:template match="/"}} {{xsl:value-of select="//PMID" /}} {{/xsl:template}} {{/xsl:stylesheet}} </cell> Putting XSL inside double curly brackets works just fine, but now I know a better way: just put it inside a CDATA [http://www.w3schools.com/xml/xml_cdata.asp] section! <map name="LibriVox"> <XSLT>./XSLT/LibriVox_to_Solr.xsl</XSLT> <nextXSL> <![CDATA[ <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text"/> <xsl:template match="/"> <xsl:variable name="baseURL" select="'%s'" /> <xsl:variable name="URL_params" select="'%s'" /> <xsl:variable name="offset_" select="substring-after($URL_params,'=')" /> <xsl:variable name="offset" select="substring-before($offset_,'&')" /> <xsl:variable name="limit_" select="substring-after($URL_params,'&')" /> <xsl:variable name="limit" select="substring-after($limit_,'=')" /> <xsl:variable name="output"> <xsl:value-of select="$baseURL" /> <xsl:text>?offset=</xsl:text> <xsl:value-of select="$offset+50" /> <xsl:text>&limit=</xsl:text> <xsl:value-of select="50" /> </xsl:variable> <xsl:value-of select="$output" /> </xsl:template> </xsl:stylesheet> ]]> </nextXSL> </map> Duh. I guess like a good XML parser that I always just ignored anything inside a CDATA section. Never thought I'd need to use one. Putting the XSL inside a CDATA section worked like a charm in terms of being able to read it with a script and perform an XSLT with it. Luckily, the PubMed2XL script can use either the CDATA way of embedding XSL or my Curly [http://en.wikipedia.org/wiki/Curly_Howard] solution - not that I knew that when I wrote it! It's certainly easier to cut/paste the XSL in the CDATA block without having to replace the brackets with curly quotes or vice versa. It's also just easier to read, which makes it easier to edit and troubleshoot. And it tastes better, too.