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

标签 xslt xpath

这是示例数据:

<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>代替。

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

关于xslt - XPath表达式选择除特定列表之外的所有XML子节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1791108/

相关文章:

javascript - 是否可以使用 XPath 获取此结果集?

python - XPath 通过正则表达式运行 text() 仅返回数字

java - 在 VTD-XML 中与 AutoPilot 一起使用时,XPath 评估失败

xml - XML 中的根节点是什么?

用于按元素名称升序排序的 XSLT 排序边缘案例

xslt - 如何从匹配属性值的节点集中获取节点?

java - 使用 apache commons 配置 xpath 查询具有属性的空 XML 元素

c# - 根据 XPath 中的属性值选择当前节点的子节点?

xslt - 使用 XSLT/XPath 查找有向无环图 (DAG) 最小元素(顶点)?

xml - 在 XSLT 转换期间删除 XML 命名空间?