首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >XPath表达式来选择除特定列表之外的所有XML子节点?

XPath表达式来选择除特定列表之外的所有XML子节点?
EN

Stack Overflow用户
提问于 2009-11-25 00:14:04
回答 2查看 81.1K关注 0票数 18

以下是示例数据:

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

假设我想选择除price和year元素之外的所有元素。我希望写一些像下面这样的东西,这显然是行不通的。

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

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2009-11-25 00:50:11

<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>所取代。

由于匹配表达式的特异性,上面的方法是有效的。match="cd/price | cd/year"match="cd/*"更具体,因此它是cd/pricecd/year元素的首选模板。不要试图排除节点,让它们通过丢弃它们来处理它们。

票数 40
EN

Stack Overflow用户

发布于 2009-11-25 00:16:01

我会开始尝试像这样的东西

"//cd/*[(name() != 'price') and (name() != 'year')]"

或者,您只需使用<xsl:apply-templates/>执行常规的递归模板匹配,然后为<price/><year/>元素创建空模板:

<xsl:template match="price"/>
<xsl:template match="year"/>
票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1791108

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档