I'm new to XSLT and have a general question.
To distinguish two elements with different attributes, it is better (also for performance) to use <xsl:template match="foo[@aOne]"> and <xsl:template match="foo[@aTwo]">
instead of an <xsl:if test="@aOne"> within one single template. And as far as I understood, this is how one should "think" in XSLT. But in my oppinion, this has the disadvantage, that it leads to redundant parts of code.
For example: The matching of an element with two attributes
<foo aOne="asdf">
...
</foo>
<foo aTwo="asdf">
...
</foo>
The template would look like this:
<xsl:template match="foo[@aOne]">
<div>
<p>
<xsl:value-of select="@aOne"/>
</p>
</div>
</xsl:template>
<xsl:template match="foo[@aTwo]">
<div>
<p>
<xsl:value-of select="@aTwo"/>
</p>
</div>
</xsl:template>
So one would have to write all the frame (like the <div> etc. in the example) several times.
Is there some kind of template design pattern like it is known from Java?
Or is it a totally wrong approach / view on programming XSLT?
Hope my idea got clear, thanks in advance for any comments.
Are the two attributes mutually exclusive? If so, I would write
<xsl:template match="foo[@aOne|@aTwo]">
<div>
<p>
<xsl:value-of select="@aOne|@aTwo"/>
</p>
</div>
</xsl:template>
If they are not mutually exclusive, then your approach of having two template rules seems inadequate: there would be four rules for the four possible combinations of @aOne being absent or present, and @aTwo being absent or present.
I don't want to draw any general rules. I think that in your specific example, you could do:
<xsl:template match="foo">
<div>
<p>
<xsl:apply-templates select="@*"/>
</p>
</div>
</xsl:template>
<xsl:template match="@aOne | @aTwo">
<xsl:value-of select="."/>
</xsl:template>
or even:
<xsl:template match="foo">
<div>
<p>
<xsl:value-of select="@aOne | @aTwo"/>
</p>
</div>
</xsl:template>
or some other variation (we don't know enough about what the input may contain).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With