KDS
KDS

Reputation: 13

XSLT: How to delete one attribute in certain children

I have Googled quite a bit, and can't figure out how to delete a particular attribute in a particular child node. In this example, I want to delete the "name" attribute, but only when under "alternate" parent items - not anywhere else. In this example, keep the "name" attribute under reference for example, but remove the ones under alternate.....

Start with this XML

    <products>
<product id="123456">
   <alternate-products>
      <alternate>
         <number>2002</number>
         <name>2002</name>            <-- want to remove this one
      </alternate>
      <alternate>
         <number>2002</number>
         <name>2002</name>            <--- remove this one too
      </alternate>
   </alternate-products>
   <references>
      <reference>
         <name>2002</name>           <-- keep this one - not under alternate
         <date>2002</date>
      </reference>
   </references>   
</products>

Desired XML:

<products>
   <product id="123456">
   <alternate-products>
      <alternate>
         <number>2002</number>
      </alternate>
      <alternate>
         <number>2002</number>
      </alternate>
   </alternate-products>
   <references>
      <reference>
         <name>2002</name>           <-- still there - good!
         <date>2002</date>
      </reference>
   </references>   
</products>

Can anyone provide some tips??

Upvotes: 1

Views: 335

Answers (2)

Rupesh_Kr
Rupesh_Kr

Reputation: 3435

You can try this:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

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

    <xsl:template match="alternate/name"/>
</xsl:stylesheet>

Upvotes: 0

michael.hor257k
michael.hor257k

Reputation: 116982

I want to delete the "name" attribute element, but only when under "alternate" parent items - not anywhere else.

Easy to do:

XSLT 1.0

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

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

<xsl:template match="alternate/name"/>

</xsl:stylesheet>

Upvotes: 2

Related Questions