I want to create an xsl:if statement that will apply a template if certain criteria is met.
Here is my XML file. I want to find parks that I can ice skate at and sort them alphabetically:
<?xml version="1.0"?>
<parks>
<park>
<park_name>MCGUANE (JOHN)</park_name>
<acres>10.3</acres>
<iceskating>0</iceskating>
</park>
<park>
<park_name>ARMOUR (PHILIP) SQUARE</park_name>
<acres>9.05</acres>
<iceskating>0</iceskating>
</park>
<park>
<park_name>FULLER (MELVILLE)</park_name>
<acres>11.31</acres>
<iceskating>1</iceskating>
</park>
<park>
<park_name>CORNELL (PAUL) SQUARE</park_name>
<acres>8.8</acres>
<iceskating>1</iceskating>
</park>
<park>
<park_name>RUSSELL (MARTIN) SQUARE</park_name>
<acres>10.05</acres>
<iceskating>2</iceskating>
</park>
</parks>
Here is my XSL file. If the child element "iceskating" contains a value greater than 0, I want it to apply a template:
<?xml version="1.0" encoding="UTF-8" ?>
<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:template match="/">
<xsl:element name="results">
<xsl:element name="iceskating_parks">
<xsl:apply-templates select="parks/park">
<xsl:sort select="park_name" order="ascending" />
</xsl:apply-templates>
</xsl:element>
</xsl:element>
</xsl:template>
<xsl:template match="iceskating" >
<xsl:if test="iceskating > 0">
<park name="{park_name}" acres="{acres}" />
</xsl:if>
</xsl:template>
I want the transformed XML file to be formatted like this:
<?xml version="1.0" encoding="UTF-8"?>
<results>
<iceskating_parks>
<park name="PARK NAME" acres="99.99"/>
<park name="PARK NAME" acres="99.99"/>
<park name="PARK NAME" acres="99.99"/>
</iceskating_parks>
</results>
CodePudding user response:
Put the condition into the apply-templates e.g.
<xsl:apply-templates select="parks/park[iceskating > 0]">
and keep the match="park"
from previous suggestions, instead of switching to match="iceskating"
.