Reputation: 168
Hej! I'm new to xslt so please excuse dumb questions and mistakes :)
I have a xml hierarchy and want to transform it into a new hierachy. This works well, but is there a simpler/more elegant way?
old:
<choice>
<sic>misericordia</sic>
<corr type="erratum">misericordiam</corr>
</choice>
new:
<app>
<lem>misericordia</lem>
<rdg witt="erratum">misericordiam</rdg>
</app>
working but long xslt:
<xsl:template match="choice">
<app>
<xsl:apply-templates/>
</app>
</xsl:template>
<xsl:template match="sic">
<lem>
<xsl:apply-templates/>
</lem>
</xsl:template>
<xsl:template match="corr[@type='erratum']">
<rdg wit="{@type}">
<xsl:apply-templates/>
</rdg>
</xsl:template>
Upvotes: 2
Views: 29
Reputation: 163322
You can make it shorter if all the template rules are doing the same thing. For example, if most of the time you only want to rename elements, then you could define a map of renamings and apply this to all elements:
<xsl:variable name="renamings" select="map{
'choice':'app',
'sic':'lem'
'corr':'rdg'}"/>
<xsl:template match="*">
<xsl:element name="{$renamings(local-name())}">
<xsl:apply-templates/>
</xsl:element>
</xsl:template>
and then you could define overriding template rules for any elements that need to do something more complicated. If you had 100 elements that you wanted to rename then this would certainly be a useful simplification; with only 3, in my view, it makes things unnecessarily complicated.
This example is XSLT 3.0 but you could do similar things in XSLT 1.0.
Upvotes: 2