DaniS.
DaniS.

Reputation: 181

xslt define namespace only for the root node

I'm writing a xslt to transform a filemaker xml export to another system. I want to add a root node and define for that the namespace like that:

<xsl:template match="*">
  <root xmlns="http://somedefinition">
    <xsl:apply-templates select="fm:ROW" />
  </root>
</xsl:template>

<xsl:template match="fm:ROW">
 <name><xsl:value-of select="fm:name"/></name>
 <name2><xsl:value-of select="fm:name2" /></name2>
 <street><xsl:value-of select="fm:street" /></street>
</xsl:template>

I call then another template. The nodes, that are created by that template get also a xmln-definition, which is empty. How can i prevent that?

the output looks like that:

<root xmlns="http://somedefinition">
  <name xmlns="">Lack AG</name>
  <name2 xmlns="">Freie Strasse</name2>
  <street xmlns="">55</street>
</root>

thx for your help

Upvotes: 0

Views: 653

Answers (1)

Ian Roberts
Ian Roberts

Reputation: 122414

That output is correct, because you're creating a root element in the http://somedefinition namespace and a number of other elements in no namespace. To serialize this accurately the processor must add the xmlns="" overrides.

To get the output you want you would need to create the name, name2 and street elements in the same http://somedefinition namespace as the root element. The simplest way to achieve that is to remove the xmlns="http://somedefinition" from the root element inside the first template, and instead put it on the xsl:stylesheet element at the root of the stylesheet document

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" 
       xmlns:fm="..."
       xmlns="http://somedefinition"><!-- and any other required namespaces -->

  <xsl:template match="*">
    <root>
      <xsl:apply-templates select="fm:ROW" />
    </root>
  </xsl:template>

  <xsl:template match="fm:ROW">
   <name><xsl:value-of select="fm:name"/></name>
   <name2><xsl:value-of select="fm:name2" /></name2>
   <street><xsl:value-of select="fm:street" /></street>
  </xsl:template>
</xsl:stylesheet>

Now all the unprefixed literal result elements in the stylesheet use the namespace declared in the xmlns="...." on the xsl:stylesheet, and they will be created in the correct namespace in the output tree. When the serializer comes to write out that tree as XML it can do so by putting an xmlns="..." on the root element only.

Upvotes: 2

Related Questions