Soham Shah
Soham Shah

Reputation: 289

Removing XML Nodes using 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.

Upvotes: 24

Views: 46331

Answers (1)

Sean B. Durkin
Sean B. Durkin

Reputation: 12729

<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>

Upvotes: 38

Related Questions