首页 > 解决方案 > 试图理解多个谓词

问题描述

我遇到了http://xpather.com,它可以让您编写 XPath 表达式。它带有一个与此类似的示例 XML 文档:

<app>
   <abstract>a</abstract>
   <description>
      <subject>s1</subject>
      <subject>s2</subject>
   </description>
   <extra-notes>
      <note>n1</note>
      <note>n2</note>
      <note>n3</note>
      <note>n4</note>
   </extra-notes>
</app>

并有一个示例 XPath 表达式:.//*[self::abstract or self::subject or self::note][position() <= 2]

结果序列为

   <abstract>a</abstract>
   <subject>s1</subject>
   <subject>s2</subject>
   <note>n1</note>
   <note>n2</note>

现在我试图理解为什么结果是这样的:第一个谓词选择所有抽象、主题和注释元素,第二个谓词将其限制为position() <= 2. 我的直觉期望是 XPath 表达式只选择两个节点(abstract 和 subject1),但它实际上从每个选定节点中选择前两个元素。到底发生了什么?

仅用于测试:这是我的简单样式表:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xsl:output indent="yes"/>
  <xsl:template match="/">
    <e>
      <xsl:copy-of select=".//*[self::abstract or self::subject or self::note][position() &lt;= 2]"/>
    </e>
  </xsl:template>
</xsl:stylesheet>

标签: xmlxsltxpath-2.0

解决方案


使用

(//*[self::abstract or self::subject or self::note])[not(position() > 2)]

有关解释,请参阅此答案

XPath 查询以获取元素的第 n 个实例

请记住[]运算符的优先级(优先级)高于//缩写。


推荐阅读