Search code examples
xmlxsltmsxml

How to suppress unnecessary xml namespace prefix declaration?


I receive this xml

<message xmlns="http://www.ns1.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <elem1 id="att1">
    <elem2 i:nil="true" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" />
  </elem1>
</message>

and I need to transform it to this using xslt (prefix changed on nil attribute)

<?xml version="1.0" encoding="utf-8"?>
<message xmlns="http://www.ns1.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <elem1 id="att1">
    <elem2 xsi:nil="true"/>
  </elem1>
</message>

I am aware that there is no semantic difference in these two. I have no control over the xml received and am informed that the output cannot have namespace declarations, other than on the root. I have tried this

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns="http://www.ns1.com"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
  exclude-result-prefixes="i">
  <xsl:output method="xml" indent="yes"/>

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

  <xsl:template match="@i:nil">
    <xsl:attribute name="xsi:nil">
      <xsl:value-of select="." />
    </xsl:attribute>
  </xsl:template>
</xsl:stylesheet>

but I get this from it

<?xml version="1.0" encoding="utf-8"?>
<message xmlns="http://www.ns1.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <elem1 id="att1">
    <elem2 xsi:nil="true" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" />
  </elem1>
</message>

The i prefix declaration on elem2 is unnecessary and not allowed by my client. I can only modify the stylesheet. Is this possible?


Solution

  • You're copying the parent element and that means (in XSLT 1.0) you're copying its namespaces too.

    Try perhaps:

    <xsl:stylesheet version="1.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
    exclude-result-prefixes="i">
    <xsl:output method="xml" indent="yes"/>
    
    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>
    
    <xsl:template match="*[@i:nil]">
        <xsl:element name="{name()}" namespace="{namespace-uri()}">
            <xsl:attribute name="xsi:nil">true</xsl:attribute>
            <xsl:apply-templates select="@*[not(name() ='i:nil')] | node()"/>
        </xsl:element>
    </xsl:template>
    
    </xsl:stylesheet>