RE: [xsl] Re: Default namespace in result document

Subject: RE: [xsl] Re: Default namespace in result document
From: "Michael Kay" <mike@xxxxxxxxxxxx>
Date: Sun, 11 Dec 2005 16:40:01 -0000
> I asked how to get this:
> <root xmlns="";>
>     <foo>
>       <blah/>
>     </foo>
> </root>
> rather than this:
> <foo:root xmlns:foo="";>
>     <foo xmlns="";>
>       <blah/>
>     </foo>
> </foo:root>
> i.e. with no more namespace attributes than necessary.

In XSLT 1.0, the serializer can add namespace nodes but it is not allowed to
remove them. So if your result tree contains the namespace node (foo, on the <root> element, and if it contains the
namespace node ("", on the <foo> element, then the
serialized output will have both the namespace declarations shown. The
serializer can choose which namespace prefix to use (it could have output
<foo:foo>) but it can't drop the namespace declaration.

So you need to write your stylesheet code in such a way that the namespace
node (foo, isn't added to the tree. Although
serializers are allowed to add namespaces, they don't usually do so without
good reason, so if you get the namespace nodes right, you're likely to get
the output you want.

When you create an element in the result tree using a literal result element
like this:

       <xsl:apply-templates mode="copy"/>

then the created <root> element will have a copy of all the namespace nodes
that were in scope in the stylesheet, which in this case includes (foo, 

When you create an element by copying an element from the source tree (using
xsl:copy or xsl:copy-of) then all the namespace nodes for the source element
are copied too, which in this case includes ("", 

This means that the only way you can be sure to avoid multiple prefixes in
the result tree is to use the same prefix in the stylesheet as you use in
the source document - which of course isn't always feasible. In principle it
shouldn't matter, because the choice of prefix in the output shouldn't be
significant. Unfortunately this is a bit of an idealisation, because some
XML vocabularies use DTDs for validation that prescribe the use of a
particular prefix.

XSLT 2.0 gives rather more control over the generation of namespaces in the
result tree, and it is rather more prescriptive about what the serializer
does. However, it can still be quite difficult to achieve exactly the effect
that you want. It's better, if you can, to ensure that the receiving
application doesn't care.

Michael Kay

Current Thread