Ashutosh Agarwal
Ashutosh Agarwal

Reputation: 183

How to copy elements from XML that satisfy a given attribute condition?

INPUT XML

<?xml version="1.0" encoding="UTF-8"?>
<breakfast_menu>
<food>
    <item name = "Belgian Waffles" price = "$5.95" calories = "650" />
    <item name = "Strawberry Belgian Waffles" price = "$7.95" calories = "900" />
</food>
</breakfast_menu>

So, basically I want to print the item that has price attribute greater than $6.

OUTPUT XML

<food>
    <item name = "Strawberry Belgian Waffles" price = "$7.95" calories = "900" />
</food>

I have to do it using XSL and I tried the same.

MY Attempt

<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
   xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<xsl:output method="html" indent="yes" />

<xsl:for-each select="breakfast_menu/food[@price &gt; 6]">
</xsl:for-each>


</xsl:template>
</xsl:stylesheet>

This isn't working . Please suggest the workaround. Thanks.

Upvotes: 1

Views: 56

Answers (2)

Iurii  Kvashuk
Iurii Kvashuk

Reputation: 409

Unluckily, I do not know the structure entire source. But if it contains only those tags, it would be enough to use this xslt:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:output method="html" indent="yes" />
   <xsl:template match="/">
      <xsl:for-each select='breakfast_menu/food/item[number(substring-after(@price,"$")) &gt; 6]'>
         <food>
            <xsl:copy-of select="."/>
         </food>
      </xsl:for-each>
   </xsl:template>
</xsl:stylesheet>

Upvotes: 3

Alone89
Alone89

Reputation: 307

Basically you have the foreach incorrect - missing the "item"

<xsl:for-each select="breakfast_menu/food[item/@price > 6]"/>

This should be fine now

Upvotes: 1

Related Questions