Removing parent node if child node is not present in xml using xslt

I am trying to transform a given XML using xslt. The caveat is that I would have to remove the parent node if the given child node is missing. I made some templates but I am stuck. Any help would be appreciated.

Xml input:

   <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 remove a Car that does not have a price element inside 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 XSLT is completely wrong, advice please.

UPDATE

Fixed what 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>

      

+3


source to share


3 answers


<?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>

      



0


source


Super close. Just change your last template to:

<xsl:template match="Car[not(Price)]"/>

      



Also, it is not wrong, but you can combine two elements xsl:output

:

<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

      

+1


source


Another 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>

      

0


source







All Articles