Search code examples
xmlxpathxslt

How to remove namespace declaration but preserve prefix in XML using XSLT


I have an XML with prefix & namespace declaration on some nodes and I would like to remove the declaration but preserve the prefix.

Current XML is showing up as below

<Body>  
<n1:ParentNode xmlns:n1="test1" xmlns:n2="test2"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
     <School>
        <n1:SchoolInfo xmlns:n1="test1">
          <SchoolID1>
             <n2:ID xmlns:n2="test2">BAS123</n2:ID>
          <SchoolID1>
        </n1:SchoolInfo>          
     </School>              
</Body>               

I would like to result to be as below

XML:

 <Body>  
<n1:ParentNode xmlns:n1="test1" xmlns:n2="test2"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
     <School>
        <n1:SchoolInfo>
          <SchoolID1>
             <n2:ID>BAS123</n2:ID>
          <SchoolID1>
        </n1:SchoolInfo>          
     </School>              
</Body>  
       
          
           
              
             

What is the easiest way to solve it using XSLT? Any help would be appreciated. Thank you!!


Solution

  • Simply use the identity transformation, the superfluous inner namespace declarations will vanish.

    I still run (the .NET version) of Saxon 10 (HE) at my site https://xsltfiddle-beta.liberty-development.net/, there, if I run e.g. the stylesheet

    <?xml version="1.0" encoding="utf-8"?>
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
      version="3.0">
    
      <xsl:mode on-no-match="shallow-copy"/>
    
    </xsl:stylesheet>
    

    against an input like

    <Body>  
    <n1:ParentNode xmlns:n1="test1" xmlns:n2="test2"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
         <School>
            <n1:SchoolInfo xmlns:n1="test1">
              <SchoolID1>
                 <n2:ID xmlns:n2="test2">BAS123</n2:ID>
              </SchoolID1>
            </n1:SchoolInfo>          
         </School>
    </n1:ParentNode>
    </Body>
    

    the result is

    <?xml version="1.0" encoding="UTF-8"?><Body>  
    <n1:ParentNode xmlns:n1="test1" xmlns:n2="test2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
         <School>
            <n1:SchoolInfo>
              <SchoolID1>
                 <n2:ID>BAS123</n2:ID>
              </SchoolID1>
            </n1:SchoolInfo>          
         </School>
    </n1:ParentNode>
    </Body>
    

    So in my experience the suggestion works with Saxon (10 and others).