December 28, 2005

Referencing the default namespace in XSLT

Filed under: HowTo, XML, XSLT | Lindsay @ 12:04 pm

This is a quick tip that I should have probably already known but figured out with a friend today. He was working on an XML file that he needed to transform that had several namespaces attached which had their own aliases as well as a default namespace with no alias:

<rdf:RDF
  xmlns:rdf=“http://www.w3.org/1999/02/22-rdf-syntax-ns#”
  xmlns:dc=“http://purl.org/dc/elements/1.1/”
  xmlns:sy=“http://purl.org/rss/1.0/modules/syndication/”
  xmlns=“http://purl.org/rss/1.0/”>

In his XSLT, the XPATH that referred to nodes in the aliased namespaces were working correctly but the references to nodes under the default (unaliased) namespace were not.

Default namespaces have always been a pain to work with when there are other aliased namespaces in an XML document, especially with the System.Xml objects that come with the .Net 1.1 framework. In the past I had used the XmlNamespaceManager to handle problems like that by assigning an alias to the default namespace, but my friend was using the newest version of .Net to do his transformation and unfortunately I don’t know how all the new XML/XSLT objects work yet. But it turns out the problem can be fixed with a just a simple addition to the XSLT file itself.

Add the default namespace to the <xsl:stylesheet> tag in your XSLT and give it your own alias (I chose defaultns):

<xsl:stylesheet version=“1.0″ xmlns:xsl=“http://www.w3.org/1999/XSL/Transform” xmlns:defaultns=“http://purl.org/rss/1.0/”>

And use your alias where ever you need to reference a node under the default namespace scope in your XSLT:

<xsl:template match=“/”>
        <xsl:apply-templates select=“defaultns:root” />
</xsl:template>

Simple, easy, and no namespace manager!

» » » » » » »
, , , , , ,