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

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

最佳答案

super 近。只需将您的最后一个模板更改为:

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

此外,这并没有错,但您可以组合您的 2 个 xsl:output 元素:

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

关于xml - 如果使用 xslt 的 xml 中不存在子节点,则删除父节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14779124/

相关文章:

xml - 在 XSLT 导入/包含中使用动态 href?

.net - 是否可以在 .net 中执行 "mixed"XML 序列化?

xml - XSLT 中的秒数

xslt - 我们可以在 xslt 的 select 语句中使用动态变量名吗?

xml - 对子树进行排序并将其存储在 xsl :variable 中

java - Retrofit 中 RSS 提要解析期间的 ValueRequiredException

c# - 在 C# 中从 SOAP 信封中提取 XML

xml - WIX 实用程序 :xmlfile File name is Source attribute

xml - 在 xslt 中格式化日期

c - iptables-restore v1.4.12 : iptables. xslt 创建错误输出:无法加载匹配 `ptcp'