I have some design issues in my xslt engine.
Quickly, I’m transforming XML documents in other XML documents (first is a metamodel, second is OpenDocument XML).
At one point, I want to output the content text node of an element based upon some conditions.
let’s use a dummy example :
<father haircolor='blond'>
<son>
some text
</son>
<sister>
some stupid text
</sister>
</father>
And I want to output the text node of <son> element if its parent is a ‘blond father’ and if it got a sister following
I have different solutions for this :
First is using precise patterns :
<xsl:template match="father[haircolor='blond']>...</xsl:template>
<xsl:template match="son[following-sibling::sister]>...</xsl:template>
Second is using mode attribute in templates :
<xsl:template match="father[haircolor='blond' and son and sister]">
<xsl:apply-template select='*' mode='ConditionsAreOk'/>
</xsl:template>
Third is using a xsl:if in the leaf template :
<xsl:template match="son">
<xsl:if test="parent::father/@haircolor = 'blond' and following-sibling::sister>
{.}
</xsl:if>
</xsl:template>
As I’m concerned with the readability and maintenability of my xslt code, I’d like to chose the best way.
To be clear, I don’t ask for help about ‘how to’, but ‘Which way is the best’.
My actual thoughts :
I think first way is the most pure XSLT but could be quite hard-core when conditions is complicated and on several elements. I will have to create several specific templates.
I have preference for the last one, because instead of several templates with specific matchs, i have just one with hardcore XPaths in the xsl:if test condition. It’s less code and less documentation (but yes, you have to document the XPath or you’ll forgot about it in 5 minutes…).
Any opinions ?
I strongly recommend to avoid as much as possible explicit conditional instructions and to use template match patterns instead.
In this particular case I’d use:
So, it is just one single template — not two — and the code inside the template body has got rid of difficult to read, understand and maintain conditional instructions.
My own principle is:
If the code contains explicit conditional instructions, then it definitely needs improvement.