Adding a Namespace to the Result Document

xslt for dummies
Chapter 15 - Namespaces Revisited
XSLT For Dummies
by Richard Wagner
Hungry Minds 2002

Now that you talk namespace and youve got your mother-in-laws QName problem solved , its time to add namespaces to your result documents. You can add namespaces to an output document by performing two steps:

  • Declaring the result documents namespace in the XSLT stylesheets stylesheet element.

  • Adding the namespace prefixes to the associated elements or attributes.

Suppose, for example, that I use the following nations.xml file as the source document, as shown in Listing 15-1.

Listing 15-1: nations.xml
start example
 <?xml version="1.0"?> <nationstates> <nation>Botswana</nation> <nation>Burkina Faso</nation> <nation>Cameroon</nation> <nation>Canada</nation> <nation>France</nation> <nation>Netherlands</nation> <nation>United Kingdom</nation> </nationstates> 
end example

In this illustration, I add a United Nations namespace to this source and generate a new result document, using the namespace URI of with a prefix of un: . To do so, a stylesheet needs to include this information as a namespace declaration:

 <xsl:stylesheet version="1.0" xmlns:xsl="" xmlns:un=""> 

In the template rules, I add the un: abbreviation onto the nationstates and nation elements. The complete stylesheet follows :

 <?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="" xmlns:un=""> <xsl:output method="xml" omit-xml-declaration="yes"/> <xsl:template match="nationstates"> <un:nationstates><xsl:apply-templates/></un:nationstates> </xsl:template> <xsl:template match="nation"> <un:nation><xsl:value-of select="."/></un:nation> </xsl:template> </xsl:stylesheet> 

When the XSLT processor transforms the source document (refer to Listing 15-1) based on this stylesheet, the result is:

 <un:nationstates xmlns:un=""> <un:nation>Botswana</un:nation> <un:nation>Burkina Faso</un:nation> <un:nation>Cameroon</un:nation> <un:nation>Canada</un:nation> <un:nation>France</un:nation> <un:nation>Netherlands</un:nation> <un:nation>United Kingdom</un:nation> </un:nationstates> 

As you can see, the XSLT processor automatically adds the xmlns declaration to the document element of the result document. The un: namespace prefixes are now included as a result of the template rules.

 Technical Stuff   If you take a quick glance at the result documents from previous chapters, it appears that I have avoided using namespaces. Actually, when you dont explicitly define a namespace, XSLT uses the default namespace. Although the default (or null) namespace has no visible presence in the document, dont confuse its implicit nature with no namespace at all.

2000-2002    Feedback

XSLT For Dummies
XSLT for Dummies
ISBN: 0764536516
EAN: 2147483647
Year: 2002
Pages: 148

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: