Tuesday, May 6, 2008

Namespace nodes for literal result elements

A recent discussion on xsl-list taught me something new about the XSLT 2.0 language. Following are my thoughts about it.

Suppose, we have this simple stylesheet:

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

<xsl:output method="xml" indent="yes" />

<xsl:template match="/">
<result>
<x/>
</result>
</xsl:template>

</xsl:stylesheet>

This stylesheet when run, produces the following output:

<?xml version="1.0" encoding="UTF-8"?>
<result xmlns:a="http://mydomain">
<x/>
</result>

Please note the xmlns:a namespace declaration in the output.

To get rid of this namespace declaration from the output, we have to do:

exclude-result-prefixes="a" on the xsl:stylesheet element, or

have literal result element be declared in the stylesheet as follows:

<result xsl:exclude-result-prefixes="a">
<x/>
</result>

The question is: Why is the namespace declaration copied to the output?

The answer can be found in the XSLT 2.0 specification, at http://www.w3.org/TR/xslt20/#lre-namespaces. As per the XSLT 2.0 specification, XSLT namespace - http://www.w3.org/1999/XSL/Transform is not copied to the output, while any other namespace nodes are copied to the output, except for few additional rules, as specified in the spec.

No comments: