Search code examples
xmlxsltxslt-2.0

Removing Header tags including envelope, body etc


I am having a souce XML in which I need to remove the Header tags and sort of extract a sub-XML from the main XML. Below is my input -

<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/ " xmlns:xs="http://www.w3.org/2001/XMLSchema " xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance " xmlns:n="http://schemas.xmlsoap.org/soap/envelope/ " xmlns:fn="http://www.w3.org/2005/xpath-functions" xmlns:event="some namespace" xmlns:head="some namespace">
    <soap:Header>
        <head:someHeader>
            <!--content-->
        </head:someHeader>
    </soap:Header>
    <soap:Body>
        <event:parent>
            <child>
                <!--internal content-->
            </child>
        </event:parent>
    </soap:Body>
</soap:Envelope>

And below is my expected output -

        <parent>
            <child>
                <!--internal content-->
            </child>
        </parent>

First I am doing Identity Transformation and then trying to remove Envelope and Body but it doesn't seems to be working. Here is my attempt which is not working -

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" exclude-result-prefixes="soap">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="soap:Envelope/soap:Header"/>
    <xsl:template match="Envelope/Body">
        <xsl:copy-of select="*"/>
    </xsl:template>
</xsl:stylesheet>

Solution

  • You could do simply:

    XSLT 2.0

    <xsl:stylesheet version="2.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" 
    xmlns:event="some namespace"
    exclude-result-prefixes="soap event">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:strip-space elements="*"/>
    
    <xsl:template match="/soap:Envelope">
        <parent>
            <xsl:copy-of select="soap:Body/event:parent/*" copy-namespaces="no"/>
        </parent>
    </xsl:template>
    
    </xsl:stylesheet>
    

    Demo: https://xsltfiddle.liberty-development.net/bEzknsY