A Stylesheet That Reproduces Its Input Document

To start our examples, we’ll look at a stylesheet that generates a document equal to the input document. (This is sometimes called an identity transform.) The stylesheet is short and sweet:

<?xml version="1.0"?>
<!-- copy-of.xsl -->
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:template match="/">
    <xsl:copy-of select="*"/>
  </xsl:template>
</xsl:stylesheet>

That’s all we have to do. Our template simply says to start with the document element of the input document and copy it to the output. <xsl:copy-of> does a deep copy of a node, so the root node and all of its children are copied to the output. If any of the root node’s descendants are element nodes with attributes, the attributes are copied as well. (Remember, an element’s attributes aren’t considered children.)

We’ll test our stylesheet against this document:

<?xml version="1.0"?>
<!-- sonnet.xml --> <sonnet type='Shakespearean'> <auth:author xmlns:auth="http://www.authors.com/"> <last-name>Shakespeare</last-name> <first-name>William</first-name> <nationality>British</nationality> <year-of-birth>1564</year-of-birth> <year-of-death>1616</year-of-death> </auth:author> <!-- Is there an official title for this sonnet? They're sometimes named after the first line. --> <title>Sonnet 130</title> <lines> <line>My mistress' eyes are nothing like the sun,</line> <line>Coral is far more red than her lips red.</line> <line>If snow be white, why then her breasts ...

Get XSLT, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.