删除父节点,如果子节点不存在使用XML XSLT(deleting the parent node

2019-07-19 15:42发布

我想变换使用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是完全错误的请指点。

UPDATE

更正其中一个工程:)

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

Answer 1:

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


Answer 2:

超近。 只要改变你的最后一个模板:

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

此外,它不是不正确,但你可以结合你的2 xsl:output的元素:

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


Answer 3:

一种不同的解决方案是使用“XSL:复制的”元素。

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


文章来源: deleting the parent node if child node is not present in xml using xslt
标签: xml xslt