ade19
ade19

Reputation: 1200

Deleting a node with XSLT

I have 2 XML sample documents as shown below

<document>

   <content name="filetype>other</content>

  <content name="filetype>xml</content>

</document>




<document>

  <content name="filetype>other</content>

 </document>

If the content tag has a filetype other than 'other', I want to delete the 'other' filetype. As such, XML 2 will remain as is since it only has the 'other' filetype while XML 1 becomes

<document>

   <content name="filetype>xml</content>

 </document> 

I have tried a number of approached to handle this but none seems to work. Below is my latest approach

<xsl:template match="content[@name='filetype']" mode="copy">


    <xsl:if test=".='other'">

       <xsl:variable name="filetypes" select="../content[@name='filetype']" />



<xsl:variable name="coun" select="count($filetypes)" />


<xsl:if test="coun = 1">

  <content name="filetype">
    other
  </content>

   </xsl:if>


  </xsl:if>


  <xsl:if test=".!='other'">

    <content name="filetype">

      <xsl:value-of select="." />

  </content>

   </xsl:if>

 </xsl:template>

How do I achieve this?

Upvotes: 0

Views: 91

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167716

Use

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

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

<xsl:template match="document[content[@name = 'filetype'] != 'other']/content[@name = 'filetype' and . = 'other']"/>

</xsl:stylesheet>

Upvotes: 2

Related Questions