views:

187

answers:

1

I am using .NET to transform XML from a DataSet to the sitemap format. Here is where I am at right now. As you can see, I create the root element with the correct namespace. I noticed that if I created child nodes, they all got an empty xmls-attribute (<url xmlns="">...</url>), unless I specified the namespace when I create the element in the template.

It's not very DRY. is there a way to define the namespace of alle elements that are created?

<xsl:template match="/">
    <!-- Root element has a namespace -->
    <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"&gt;
        <xsl:apply-templates/>
    </urlset>
</xsl:template>

<xsl:template match="Document">
    <!-- Do it this way to prevent empty xmlns attribute on element -->
    <xsl:element name="url" namespace="http://www.sitemaps.org/schemas/sitemap/0.9"&gt;
        <!-- This element will get the empty xmlns attribute, unless I create it like the url element -->
        <location>
            <xsl:value-of select="Path" />
        </location>
        <!-- There are more elements to create here, do I have to specify the namespace each time? -->
    </xsl:element>
</xsl:template>

Thanks!

+2  A: 

Specify the default namespace on the root of the stylesheet.

<xsl:stylesheet version="1.0" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;

Or, in my opinion a preferred solution, define a prefix on the root and use it later for your elements:

<xsl:stylesheet version="1.0" xmlns:sm="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;
    <xsl:template match="/">
        <sm:urlset>
            <xsl:apply-templates/>
        </sm:urlset>
    </xsl:template>
Lucero
Doh! That simple. I prefer the first solution. Thanks!
michielvoo
The first solution has the drawback of giving you trouble in XPath queries if you need to use the empty namespace, and it also prevents you from creating fully qualified attributes. Also, it may be more confusing for the reader because the prefix helps associate the element to the correct namespace when reading, especially in documents with several namespaces. That said, the solutions are pretty much equivalent, and you can control the output of the `xmlns` attributes via `exclude-result-prefixes` attribute on the stylesheet and the `xsl:namespace-alias` element.
Lucero