Search code examples
xsltstylesheet

XSLT to remove few nodes and get a given node with its child nodes


Input

<?xml version='1.0' encoding='utf-8'?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body><jsonObject>
<User>
<No>123</No>
<Id>1</Id>
<MailCode>43</MailCode>
<Number>998</Number>
</User>
</jsonObject></soapenv:Body>
</soapenv:Envelope>

Expected Output

<User xmlns="http://sample.org">
<No>123</No>
<Id>1</Id>
<MailCode>43</MailCode>
<Number>998</Number>
</User>

Current XSLT

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


<xsl:template match="jsonObject">
</xsl:template>

<xsl:template match="User">
        <!--Define the namespace -->
        <xsl:element name="{local-name()}" namespace="http://sample.org">
            <!--apply to above selected node-->
             <xsl:apply-templates select="node()|@*">

        </xsl:apply-templates></xsl:element>
    </xsl:template>


</xsl:stylesheet>

But the current output is,

<User xmlns="http://sample.org">
123
1
43
998
</User>

What am I doing wrong here? Also is there any way to directly extract the content of <User> node instead of writing separate templates to remove nodes like <jsonObject>?


Solution

  • The expected output can be achieved by applying the following stylesheet:

    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="User | User/*" >
        <xsl:element name="{local-name()}" namespace="http://sample.org">
            <xsl:apply-templates/>
        </xsl:element>
    </xsl:template>
    
    </xsl:stylesheet>