I have a series of medium-sized XML documents, which are mainly text with a few nodes representing macros to be expanded, e.g.:
<foo>Some text <macro>A1</macro> ... <macro>B2</macro> ...etc...</foo>
My goal is to replace each macro with the corresponding XML. Usually it's a single <img>
tag with different attributes, but it could be some other HTML as well.
The stylesheet is generated programatically, and one way to do that would be to have a template per macro, e.g.
<xsl:template match="macro[.='A1']">
<!-- content goes here -->
</xsl:template>
<xsl:template match="macro[.='A2']">
<!-- other content goes here -->
</xsl:template>
<xsl:template match="macro[.='B2']">
<!-- etc... -->
</xsl:template>
It works just fine, but it can have up to a hundred macros and it's not very performant (I'm using libxslt.) I've tried a couple of alternative such as:
<xsl:template match="macro">
<xsl:choose>
<xsl:when test=".='A1'">
<!-- content goes here -->
</xsl:when>
<xsl:when test=".='A2'">
<!-- other content goes here -->
</xsl:when>
<xsl:when test=".='B2'">
<!-- etc... -->
</xsl:when>
</xsl:choose>
</xsl:template>
It's slightly more performant. I have tried adding another level of branching such as:
<xsl:template match="macro">
<xsl:choose>
<xsl:when test="substring(.,1,1) = 'A'">
<xsl:choose>
<xsl:when test=".='A1'">
<!-- content goes here -->
</xsl:when>
<xsl:when test=".='A2'">
<!-- other content goes here -->
</xsl:when>
</xsl:choose>
</xsl:when>
<xsl:when test=".='B2'">
<!-- etc... -->
</xsl:when>
</xsl:choose>
</xsl:template>
It loads slightly slower (the XSL is bigger and a bit more complicated) but it executes slightly faster (each branch can eliminate several cases.)
Now I am wondering, is there a better way to do that? I have around 50-100 macros. Normally, the transformation is executed using libxslt but I can't use proprietary extensions from other XSLT engines.
Any input is welcome :)