Igor Grinfeld
Igor Grinfeld

Reputation: 598

Simplest XSLT to filter nodes based on child node attribute value

I want to use XSLT for copying mrss xml, but filter items that don't have test value in label attribute using XSLT.

Here is what I did so far:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:media="http://search.yahoo.com/mrss/"> 
    <xsl:template match="/">
        <rss xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
            <channel><xsl:apply-templates/></channel>
        </rss>      
    </xsl:template>

   <xsl:template match="channel/item[contains(media:category/@label,'test')] | channel/*[not(self::item)]">
        <xsl:copy-of select="."/>
   </xsl:template>

   <xsl:template match="channel/item[not(contains(media:category/@label,'test'))]">
   </xsl:template>
</xsl:stylesheet>

Three things that I don't like in it:

Can somebody can suggest better/simpler solution?

Upvotes: 2

Views: 4860

Answers (1)

JLRishe
JLRishe

Reputation: 101710

Yes, the better approach is to start with an identity template and go from there. The following should be all you need:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                              xmlns:media="http://search.yahoo.com/mrss/">
  <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="channel/item[not(contains(media:category/@label,'test'))]" />
</xsl:stylesheet>

Upvotes: 3

Related Questions