Amit Singh
Amit Singh

Reputation: 49

Remove empty xmlns attributes

This is my input xml <a><b><![CDATA[This is a text]]></b></a>

This is my xsl

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
version="1.0">

<xsl:template match="/">
 <xsl:apply-templates select="//b" />
</xsl:template>

<xsl:template match="b">
 <xsl:choose>                                                       
  <xsl:when test=".='This is a text'">
    <e xmlns="www.example.com">
      <f>yes</f>
      <g>
          <xsl:call-template name="atemp"/>
      </g>
    </e>
  </xsl:when>                                                                      
  <xsl:otherwise>
   <d>NO</d>                                                         
  </xsl:otherwise>
 </xsl:choose>
</xsl:template>

<xsl:template name="atemp">
  <l>l</l>
  <m>m</m>
  <n>n</n>
</xsl:template>

</xsl:stylesheet>

This is the output xml-

<?xml version="1.0" encoding="UTF-8"?>

<e xmlns="www.example.com">
 <f>yes</f>
 <g>
  <l xmlns="">l</l>
  <m xmlns="">m</m>
  <n xmlns="">n</n>
 </g>
</e>

I want those xmlns="" in l,m,n tags to be gone. This code is part of a large Java project. Interesting thing is these xmlns="" are not being produced in my colleague's computer, even when we both have the same code. Here is the running code http://xsltfiddle.liberty-development.net/3NzcBtS/1

This is the output I want-

<?xml version="1.0" encoding="UTF-8"?>

<e xmlns="www.example.com">
 <f>yes</f>
 <g>
  <l>l</l>
  <m>m</m>
  <n>n</n>
 </g>
</e>

What should I do?

Upvotes: 1

Views: 430

Answers (1)

kjhughes
kjhughes

Reputation: 111726

Change

<xsl:template name="atemp">
  <l>l</l>
  <m>m</m>
  <n>n</n>
</xsl:template>

to

<xsl:template name="atemp">
  <l xmlns="www.example.com">l</l>
  <m xmlns="www.example.com">m</m>
  <n xmlns="www.example.com">n</n>
</xsl:template>

in order to place l, m, and n in the www.example.com namespace. Since the www.example.com default namespace is already declared on e, and since these elements are descendents of e, you'll eliminate the xmlns="" from these elements, as requested.


Or, factored out to xsl:template via a good suggestion from @TimC:

<xsl:template name="atemp" xmlns="www.example.com">
  <l>l</l>
  <m>m</m>
  <n>n</n>
</xsl:template>

Or, factored all the way out to xsl:stylesheet:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                version="1.0"
                xmlns="www.example.com">

Upvotes: 3

Related Questions