Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing XML Nodes using XSLT

Tags:

xml

xslt

I have the following XML:

<?xml version="1.0" encoding="utf-8"?>
<Rowsets>
<Rowset>
    <Columns>
        <Column Description="FirstName" MaxRange="1" MinRange="0" Name="FirstName" SQLDataType="12" SourceColumn="FirstName"/>
        <Column Description="LastName" MaxRange="1" MinRange="0" Name="LastName" SQLDataType="12" SourceColumn="LastName"/>
        <Column Description="Phone" MaxRange="1" MinRange="0" Name="Phone" SQLDataType="1" SourceColumn="Phone"/>
    </Columns>
    <Row>
        <FirstName>Michael</FirstName>
        <LastName>David</LastName>
        <Phone>1234567890</Phone>
    </Row>
    <Row>
        <FirstName>David</FirstName>
        <LastName>Michael</LastName>
        <Phone>01234567890</Phone>
    </Row>
    <Row>
        <FirstName>Yang</FirstName>
        <LastName>Christina</LastName>
        <Phone>2345678901</Phone>
    </Row>
    <Row>
        <FirstName>Grey</FirstName>
        <LastName>Meredith</LastName>
        <Phone>3456789012</Phone>
    </Row>
    <Row>
        <FirstName>David</FirstName>
        <LastName>Shepherd</LastName>
        <Phone>5678901234</Phone>
    </Row>
</Rowset>

I want to remove <Phone> node from every Row as well as from Column description.

SO my resultant XML would look like following:

<?xml version="1.0" encoding="utf-8"?>
<Rowsets>
<Rowset>
    <Columns>
        <Column Description="FirstName" MaxRange="1" MinRange="0" Name="FirstName" SQLDataType="12" SourceColumn="FirstName"/>
        <Column Description="LastName" MaxRange="1" MinRange="0" Name="LastName" SQLDataType="12" SourceColumn="LastName"/>
    </Columns>
    <Row>
        <FirstName>Michael</FirstName>
        <LastName>David</LastName>
    </Row>
    <Row>
        <FirstName>David</FirstName>
        <LastName>Michael</LastName>
    </Row>
    <Row>
        <FirstName>Yang</FirstName>
        <LastName>Christina</LastName>
    </Row>
    <Row>
        <FirstName>Grey</FirstName>
        <LastName>Meredith</LastName>
    </Row>
    <Row>
        <FirstName>David</FirstName>
        <LastName>Shepherd</LastName>
    </Row>
</Rowset>

How do I achieve that? I tried various XSLT but I am not able to do it.

like image 591
Soham Shah Avatar asked Aug 28 '12 03:08

Soham Shah


1 Answers

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

<xsl:template match="@*|node()">
 <xsl:copy>
  <xsl:apply-templates select="@*|node()"/>
 </xsl:copy>
</xsl:template>

<xsl:template match="Column[@SourceColumn='Phone']|Phone" />

</xsl:stylesheet>
like image 66
Sean B. Durkin Avatar answered Nov 20 '22 20:11

Sean B. Durkin