Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract a subset of XML file using XSL

Tags:

xml

xslt

I have this XML file:

<Response>
    <errorCode>error Code</errorCode>
    <errorMessage>msg</errorMessage>
    <ResponseParameters>
        <className>
            <attribute1>a</attribute1>
            <attribute2>b</attribute2>
        </className>
    </ResponseParameters>
</Response>

And I want the output to be:

<className>
    <attribute1>a</attribute1>
    <attribute2>b</attribute2>
</className>

My current XSL file is including also "ResponseParameters" tag, which I do not want.

EDIT: note that the node className is dynamic. I do not know what will be this name at runtime.

<?xml version="1.0"?>

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

    <xsl:output indent="yes" />

    <xsl:template match="/">
        <xsl:copy-of select="//ResponseParameters">
        </xsl:copy-of>
    </xsl:template>
</xsl:stylesheet>
like image 579
Lucas Pottersky Avatar asked Feb 25 '09 16:02

Lucas Pottersky


3 Answers

Use :

<xsl:copy-of select="/Response/ResponseParameters/node()"/>

The "//" abbreviation is very expensive (causes the complete XML document to be scanned), and should be avoided.

like image 131
Dimitre Novatchev Avatar answered Sep 28 '22 17:09

Dimitre Novatchev


<xsl:copy-of select="Response/ResponseParameters//*"/>
like image 29
Nick Allen Avatar answered Sep 28 '22 15:09

Nick Allen


One way is to pass a parameter containing the node name into the XSLT and use the parameter passed in with the name() function to match the dynamic node.

Edit:

But in this simple case either of the other answers suggesting ResponseParameters//* or ResponseParameters/* are a far simpler solution.

like image 28
andynormancx Avatar answered Sep 28 '22 17:09

andynormancx