user2788521
user2788521

Reputation: 1

How to remove XML elements based on attribute in XSLT

I am struggling with some basic XSLT. I would like to remove an element from some XML depending on whether it has not got a certain attribute(In this case PriorValue).

The XML Looks like this The XML is not limited to only the below sections, it has a lot of other sections and the same logic is applied to them as well.

   <Emp>
       <Personal>
            <First_Name>abc</First_Name>
            <Last_Name>xyz</Last_Name>
            <Gender>1</Gender>
            <Birth_Date PriorValue="1980-08-05">1980-09-05</Birth_Date>
            <Country_of_Birth PriorValue="600">724</Country_of_Birth>
            <Marital_Status PriorValue="0">1</Marital_Status>
        </Personal>
        <Info>
            <Name>abc</Name>
            <ID>Part time</ID>
            <NoOfProbationDays>0</NoOfProbationDays>
            <EMPtype>0</EMPtype>
            <CountryOfBirth PriorValue="IND">ESP</CountryOfBirth>
        </Info>
    </Emp>

The desired XML output looks like this.

    <Emp>
        <Personal>
            <Birth_Date PriorValue="1980-08-05">1980-09-05</Birth_Date>
            <Country_of_Birth PriorValue="600">724</Country_of_Birth>
            <Marital_Status PriorValue="0">1</Marital_Status>
        </Personal>
        <Info>
            <CountryOfBirth PriorValue="IND">ESP</CountryOfBirth>
        </Info>
    </Emp>

Thanks for your help.

Upvotes: 0

Views: 251

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167716

Use

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

<xsl:template match="*[not(*) and not(@PriorValue)]"/>

Upvotes: 2

Related Questions