xsl:namespace (2)

  1. namespace_2-input.xml

  2. <?xml version="1.0"?>
    <products>
      <product id="p1" price="1000"/>
      <product id="p2" price="1200"/>
      <product id="p3" price="1250"/>
    </products>
  1. namespace_2-stylesheet.xsl

  2. <?xml version="1.0"?>
    <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
      <xsl:output indent="yes"/>
      <xsl:param name="ns-prefix" select="'x'"/>
      <xsl:param name="ns-namespace" select="'someNamespace'"/>

      <xsl:template match="products">
        <catalog>
          <xsl:namespace name="{$ns-prefix}" select="$ns-namespace"/>
          <xsl:apply-templates/>
        </catalog>
      </xsl:template>

      <xsl:template name="start" match="product">
        <xsl:element name="{$ns-prefix}:product" namespace="{$ns-namespace}">
          <xsl:attribute name="id" select="@id"/>
          <xsl:attribute name="price" select="@price"/>
        </xsl:element>
      </xsl:template>
    </xsl:stylesheet>
  1. namespace_2-output.xml

  2. <?xml version="1.0" encoding="UTF-8"?>
  3. <catalog xmlns:x="someNamespace">
  4.   <x:product id="p1" price="1000"/>
  5.   <x:product id="p2" price="1200"/>
  6.   <x:product id="p3" price="1250"/>
  7. </catalog>

Comment

In the above example xsl:namespace is only used for cosmetic reasons in order to transfer the namespace declaration from each child element to outermost element. The parameters are only to indicate that we are talking about some dynamic creation of the namespace. For a dynamic solution we need to use xsl:namespace also for literally result elemens. See my tutorial xsl:namespace in XSLT 2.0

Updated 2009-03-19