Reputation: 467
I am trying to transform a given XML using xslt. The caveat is that I would have to delete a parent node if a given child node is not present. I did do some template matching, but I am stuck. Any help would be appreciated.
The input xml :
<Cars>
<Car>
<Brand>Nisan</Brand>
<Price>12</Price>
</Car>
<Car>
<Brand>Lawrence</Brand>
</Car>
<Car>
<Brand>Cinrace</Brand>
<Price>14</Price>
</Car>
</Cars>
I would like to delete the Car which doesn't have the price element within it. So the expected output is :
<Cars>
<Car>
<Brand>Nisan</Brand>
<Price>12</Price>
</Car>
<Car>
<Brand>Cinrace</Brand>
<Price>14</Price>
</Car>
</Cars>
I tried using this :
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:strip-space elements="*" />
<xsl:output omit-xml-declaration="yes"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Cars/Car[contains(Price)='false']"/>
</xsl:stylesheet>
I know the XSLT is totally wrong please advice.
UPDATE
Corrected one which works :)
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<!--Identity template to copy all content by default-->
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Car[not(Price)]"/>
</xsl:stylesheet>
Upvotes: 4
Views: 2697
Reputation: 1920
A different solution is to use the 'xsl:copy-of' element.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output method="xml" />
<xsl:template match="Cars">
<xsl:copy>
<xsl:copy-of select="Car[Price]" />
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Upvotes: 0
Reputation: 3162
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<!--Identity template to copy all content by default-->
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Car[not(Price)]"/>
</xsl:stylesheet>
Upvotes: 0
Reputation: 52858
Super close. Just change your last template to:
<xsl:template match="Car[not(Price)]"/>
Also, it's not incorrect but you can combine your 2 xsl:output
elements:
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
Upvotes: 2