Site Banner Graphic

Duplicating and Editing the Document Element

How to use copy and copy-of to make small edits

Need to add one to every index value in your Xml? Misspell a word--a thousand times over? Never fear--use Xslt to patch it up‼

Here is some annotated Xslt that shows an easy method to copy most information in a source document, changing select elements along the way.  

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet
  version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <!--  //    Output will be near identical copy of input Xml -->
  <xsl:output method="xml" indent="yes"/>

  <!--  //    Match and copy root input -->
  <xsl:template match="/">
    <!--  //    Copy the passed element… -->
    <xsl:copy>
      <!--  //    …and all of its attributes… -->
      <xsl:copy-of select="@*"/>
      <!--  //    …then apply templates to children. -->
      <xsl:apply-templates />
    </xsl:copy>
  </xsl:template>

  <!--  //    Match all attributes and nodes except root -->
  <xsl:template match="@* | child::node()">
    <!--  //    Copy the passed element… -->
    <xsl:copy>
      <!--  //    …and all of its attributes… -->
      <xsl:copy-of select="@*"/>
      <!--  //    …then apply templates to children. -->
      <xsl:apply-templates />
    </xsl:copy>
  </xsl:template>

  <!--  //    Change these elements in this manner during copy -->
  <!--  //    This match overrides the more general template above -->
  <xsl:template match="Index">
    <!--  //    Copy the passed element… -->
    <xsl:copy>
      <!--  //    …and all of its attributes… -->
      <xsl:copy-of select="@*"/>
      <!--  //    …free up odd numbers. -->
      <xsl:value-of select=". * 2"/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>