Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change the namespace of an element with xslt

Tags:

xml

xslt

I'd like to make this

<hello>
  <one>
    <paragraph>p1</paragraph>
  </one>
</hello> 

into this

<x:hello y:an_attribute="a value for an_attribute" xmlns:x="some_new_namespace" xmlns:y="other_ns">
  <one>
    <paragraph>p1</paragraph>
  </one>
</x:hello> 

this is the stylesheet I came up with:

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>

    <xsl:param name="element_localname" select="'hello'"/>


    <xsl:template match="node()">
        <xsl:choose>
            <xsl:when test="local-name() = $element_localname">
                <xsl:element name="{$element_localname}" namespace="some_new_namespace">
                    <xsl:attribute name="an_attribute" namespace="other_ns">a value for an_attribute</xsl:attribute>
                    <xsl:apply-templates select="node()"/>
                </xsl:element>
            </xsl:when>

            <!-- copy the rest as is -->
            <xsl:otherwise> 
                <xsl:copy>
                    <xsl:apply-templates select="node()" />
                </xsl:copy>
            </xsl:otherwise>

        </xsl:choose>
    </xsl:template>

</xsl:stylesheet> 

but for some strange reason, the attribute I am adding to the element has the same namespace as the root element itself? why?

<ns0:hello xmlns:ns0="other_ns" ns0:an_attribute="a value for an_attribute">
  <one>
    <paragraph>p1</paragraph>
  </one>
</ns0:hello>

Thank you for reading.

like image 212
Luca Avatar asked Oct 14 '22 21:10

Luca


1 Answers

This is much simpler than it might seem:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:x="some_new_namespace" xmlns:y="other_ns"
 exclude-result-prefixes="x y">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="node()|@*">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>

 <xsl:template match="/*">
  <x:hello y:an_attribute="a value for an_attribute">
   <xsl:apply-templates/>
  </x:hello>
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied to the provided XML document:

<hello>
    <one>
        <paragraph>p1</paragraph>
    </one>
</hello>

the wanted, correct result is produced:

<x:hello xmlns:x="some_new_namespace" xmlns:y="other_ns" y:an_attribute="a value for an_attribute">
    <one>
        <paragraph>p1</paragraph>
    </one>
</x:hello>
like image 89
Dimitre Novatchev Avatar answered Jan 09 '23 15:01

Dimitre Novatchev