1
votes

I am not very familiar with XSLT. I am trying to remove the xmlns namespace from the root tag while preserve other tags like xmlns:xsd and xmlns:xsi using xslt. I got some help from internet to remove the xmlns namespace but that code is also removing xmlns:xsd. Please help. Thanks in advance.

This is my xsl code:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0"
 xmlns:old="http://www.example.com"    exclude-result-prefixes="old">

<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

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


<xsl:template match="old:*">
   <xsl:element name="{local-name()}">
      <xsl:apply-templates select="@* | node()"/>
    </xsl:element>
</xsl:template>
</xsl:stylesheet> 

This is my input xml:

<?xml version="1.0" encoding="UTF-8"?>
<Data xmlns="http://www.example.com" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
 xsi:schemaLocation="http://www.example.com/schemaLocation">

<name>abc</name>
<name>efg</name>

</Data>

On running my XSL on the input XML I get the following XML

<?xml version="1.0" encoding="UTF-8"?>
<Data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.example.com/schemaLocation">

<name>abc</name>
<name>efg</name>

</Data>

Desired Output XML:

<?xml version="1.0" encoding="UTF-8"?>
<Data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
 xsi:schemaLocation="http://www.example.com/schemaLocation">

<name>abc</name>
<name>efg</name>

</Data>
1
Note: you're not "trying to remove the xmlns namespace from the root tag". You want to move all elements out of their namespace (defined as the default namespace in the root element opening tag) into no-namespace - essentially renaming all elements in the given XML document.michael.hor257k

1 Answers

0
votes

The missing namespace declaration is not used anywhere in the XML document, so your processor is quite right in discarding it.

You may try and force it to be copied:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="*">
    <xsl:element name="{local-name()}">
        <xsl:copy-of select="@* | namespace::*[name()]"/>
        <xsl:apply-templates select="node()"/>
    </xsl:element>
</xsl:template>

</xsl:stylesheet>

but not all processors will produce the hoped-for result (Xalan, for example, won't).