Augmenting XML using XSLT

In order to augment a piece of XML using XSLT, the base requirement is to make sure the existing document or fragment is preserved. This is done by recursively copying all the elements, attributes etc. as defined by the W3C Recommendation for copying.

<xsl:template match="@*|node()"> 
  <xsl:copy>
    <xsl:apply-templates select="@*|node()"/> 
  </xsl:copy> 
</xsl:template>

The main things going are here is the matching of every attribute with “@*” and every child node (node() being shorthand for child::node()). As mentioned in the W3C Recommendation, the root node is considered a special case and is implicit, therefore “@*|node()” finds everything else.

This is all well and good, but the benefit of this recursive copying is making the exceptions or augmentations to the input XML. To implement these we simply add templates matching the point of change:

<xsl:template match="existingElement" > 
  <xsl:element name="replacementElement"> 
    <xsl:text>Some content for the new element</xsl:text> 
  </xsl:element> 
</xsl:template>

A really good description and set of examples of doing this sort of thing (also known as the identity template) can be found here.

comments powered by Disqus