如果xml中不存在子节点,则使用xslt删除父节点



我正在尝试使用xslt转换给定的XML。需要注意的是,如果给定的子节点不存在,我将不得不删除父节点。我确实做了一些模板匹配,但我被卡住了。如有任何帮助,我们将不胜感激。

输入xml:

   <Cars>
      <Car>
        <Brand>Nisan</Brand>
        <Price>12</Price>
     </Car>
     <Car>
        <Brand>Lawrence</Brand>
     </Car>
     <Car>
       <Brand>Cinrace</Brand>
       <Price>14</Price>
     </Car>
   </Cars>

我想删除里面没有价格元素的汽车。因此,预期输出为:

 <Cars>
      <Car>
        <Brand>Nisan</Brand>
        <Price>12</Price>
     </Car>
     <Car>
       <Brand>Cinrace</Brand>
       <Price>14</Price>
     </Car>
   </Cars>

我试过使用这个:

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

我知道XSLT是完全错误的,请给我建议。

更新

修正了一个有效的:)

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

超级关闭。只需将您的最后一个模板更改为:

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

此外,这也没有错,但你可以组合你的两个xsl:output元素:

<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
<?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>

另一种解决方案是使用'xsl:copy-of'元素。

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

最新更新