微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

xslt – XPath表达式,以选择除特定列表之外的所有XML子节点?

以下是示例数据:
<catalog>
    <cd>
        <title>Empire Burlesque</title>
        <artist>Bob Dylan</artist>
        <country>USA</country>
                <customField1>Whatever</customField1>
                <customField2>Whatever</customField2>
                <customField3>Whatever</customField3>
        <company>Columbia</company>
        <price>10.90</price>
        <year>1985</year>
    </cd>
    <cd>
        <title>Hide your heart</title>
        <artist>Bonnie Tyler</artist>
        <country>UK</country>
                <customField1>Whatever</customField1>
                <customField2>Whatever</customField2>
        <company>CBS Records</company>
        <price>9.90</price>
        <year>1988</year>
    </cd>
    <cd>
        <title>Greatest Hits</title>
        <artist>Dolly Parton</artist>
        <country>USA</country>
                <customField1>Whatever</customField1>
        <company>RCA</company>
        <price>9.90</price>
        <year>1982</year>
    </cd>
</catalog>

说我想选择除价格和年份元素之外的所有内容。我会期待写下像下面这样的东西,这显然不行。

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
  <html>
  <body>
  <xsl:for-each select="//cd/* except (//cd/price|//cd/year)">
    Current node: <xsl:value-of select="current()"/>
    <br />
  </xsl:for-each>
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>

请帮我找到一种排除某些子元素的方法

<xsl:for-each select="//cd/*[not(self::price or self::year)]">

但实际上这是坏的,不必要的复杂。更好:

<xsl:template match="catalog">
  <html>
    <body>
      <xsl:apply-templates select="cd/*" />
    </body>
  </html>
</xsl:template>

<!-- this is an empty template to mute any unwanted elements -->
<xsl:template match="cd/price | cd/year" />

<!-- this is to output wanted elements -->
<xsl:template match="cd/*">
  <xsl:text>Current node: </xsl:text>
  <xsl:value-of select="."/>
  <br />
</xsl:template>

避免< xsl:for-each>。几乎所有的时间都是错误的工具,应该由< xsl:apply-templates>替代和< xsl:template&gt ;. 以上工作原因是匹配表达特异性。 match =“cd / price | cd / year”比match =“cd / *”更具体,因此它是cd / price或cd / year元素的首选模板。不要尝试排除节点,让他们丢弃它们来处理它们。

原文地址:https://www.jb51.cc/xml/293232.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。