Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove default namespace and keep the rest of namespaces using XSLT?

I have a XML file having default namespace and empty namespaces which need to be removed, while keeping the rest of namespaces.

Input:

<prefix:request xmlns:prefix="urn1" xmlns:foo2="urn2" xmlns="urn1">
<element1 xmlns="">version1</element1>
<element2 xsi:type="prefix:requestA" xmlns=""/>
...
</element1>
</prefix:request>

Expected output:

<prefix:request xmlns:prefix="urn1" xmlns:foo2="urn2">
<element1>version1</element1>
<element2 xsi:type="prefix:requestA"/>
...
</element1>
</prefix:request>

XSLT sample for removing namespaces will filter out all namespaces, including the prefix. Any idea how to solve this particular case?

like image 737
sari Avatar asked Nov 05 '22 16:11

sari


1 Answers

This short transformation:

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

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

when applied on the (severely malformed and having to be corrected) provided XML-like input:

<prefix:request xmlns:xsi="Undefined !!!"
xmlns:prefix="urn1" xmlns:foo2="urn2"
xmlns="urn1">
    <element1 xmlns="">version1</element1>
    <element2 xsi:type="prefix:requestA" xmlns=""/> ...  
</prefix:request>

produces the wanted, correct result:

<prefix:request xmlns:prefix="urn1" xmlns:xsi="Undefined !!!" xmlns:foo2="urn2">
   <element1>version1</element1>
   <element2 xsi:type="prefix:requestA"/> ...  
</prefix:request>
like image 91
Dimitre Novatchev Avatar answered Nov 09 '22 11:11

Dimitre Novatchev