Adding processing instructions and comments using XSLT

I have been playing with XSLT. I have learned how to return the entire XML document, adding an attribute here, an element there. But how do you insert a processing instruction or comment into your document?

This XSLT will simply copy your XML document, formatting it a little:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
>
  <xsl:output method="xml" indent="yes"/>
  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

The template element responds to a section of XML that matches the match attribute. In this case the match if one of two kinds of nodes occur. @* matches any attribute and node() matches any other node, including elements, processing instructions, comments, etc. When any of these nodes (ie. anything) is found, make a copy and apply the template to the child attributes and nodes that are found. By default, the text is output. Thus this copies the entire document.

If I want to put a processing instruction and comment before the root node of the document, I make the following change:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
>
  <xsl:output method="xml" indent="yes"/>
    <xsl:template match="/">
    	<xsl:processing-instruction name="test"><xsl:text>value="1.0"</xsl:text></xsl:processing-instruction>
 	<xsl:comment><xsl:text>Something brilliant.</xsl:text></xsl:comment>
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>
  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

The template with the match equal to “/” matches the root node. What this does is to first create a processing-instruction with the name “test” and the text value=”1.0″. It creates this:

<xsl:processing-instruction name="test"><xsl:text>value="1.0"</xsl:text></xsl:processing-instruction>

Produces:

<?test value="1.0"?>

Then it creates a comment.

<xsl:comment><xsl:text>Something brilliant.</xsl:text></xsl:comment>

Produces

<!--Something brilliant.-->

Pretty powerful for a little bit of code!

About Russ

Russ Loski is a data warehouse developer focusing on SSIS and SQL Server development. He has worked with SQL Server since 1998. He has used various technologies to move data from one source to others. He has worked for well-known companies such as the Bank of America, the Dallas Cowboys Football Club, T-Mobile and Coca Cola Enterprises. Currently he is developing a Data Warehouse for a large health care organization.
This entry was posted in XML, XSLT. Bookmark the permalink.

Leave a Reply