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>
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…