【问题标题】:deleting the parent node if child node is not present in xml using xslt如果 xml 中不存在子节点,则使用 xslt 删除父节点
【发布时间】:2013-02-08 18:35:04
【问题描述】:

我正在尝试使用 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>

【问题讨论】:

  • +1 表示一个好的 XSLT 问题的所有 3 个元素。输入,输出,你尝试了什么。

标签: xml xslt


【解决方案1】:

超级接近。只需将上一个模板更改为:

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

此外,这不是错误的,但您可以组合 2 个 xsl:output 元素:

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

【讨论】:

  • 身份模板似乎错误。请指教,它没有用。
  • @hackmabrain 嗯?我没有使用身份模板。我只给了你最后一个模板的替代品。
【解决方案2】:
<?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>

【讨论】:

  • 您的身份模板中的car() 是什么?你不是说node()吗?
【解决方案3】:

另一种解决方案是使用“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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多