xml - 递归 XPath 的条件

标签 xml xpath recursive-regex

如何在 XPath 中使用递归和条件选择?

例如,给定此文档:

<root xmlns:foo="http://www.foo.org/" xmlns:bar="http://www.bar.org">
  <file name="foo.mp4">
    <chunks>
      <file>
        <chunks>
          <file>
          <chunks>
            <file>1</file>
            <file>2</file>
            <file>3</file>
            <file>4</file>
          </chunks>
          </file>
          <file>
          <chunks>
            <file>5</file>
            <file>6</file>
            <file>7</file>
            <file>8</file>
          </chunks>
          </file>
        </chunks>
      </file>
      <file>
        <chunks>
          <file>
          <chunks>
            <file>9</file>
            <file>10</file>
            <file>11</file>
            <file>12</file>
          </chunks>
          </file>
          <file>
          <chunks>
            <file>13</file>
            <file>14</file>
            <file>15</file>
            <file>16</file>
          </chunks>
          </file>
        </chunks>
      </file>
    </chunks>
  </file>
</root>

我只想选择:

<file>1</file>
<file>2</file>
<file>3</file>
<file>4</file>

所以,实际上是这样的:

//[name="foo.mp4"]/chunks/*[1]/chunks/*[1]/*

但使用通用方法——即可以覆盖更深嵌套对象的方法。像这样:

//[name="foo.mp4"]/(chunks/*[1]/)+/*

(cond)+ 不是 XPath 语法,而是我想要的类似正则表达式的表示。

最佳答案

递归意味着自引用并且在 XPath 中不直接可用。忽略中间元素级别的常用方法是通过 descendant-or-self 轴 (//),由所需属性锚定。

例如,以下每个 XPath 表达式,

  • 所有值小于 5 的 file 元素:

    //file[number() < 5]
    
  • 前 4 个叶 file 元素:

    //file[not(*)][count(preceding::file[not(*)]) < 4]
    
  • 祖先没有前辈的file叶元素:

    //file[not(*)][not(ancestor::*[preceding::*])]
    

会选择

<file>1</file>
<file>2</file>
<file>3</file>
<file>4</file>

根据要求。

关于xml - 递归 XPath 的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35530528/

相关文章:

.net - 将PCRE递归正则表达式模式转换为.NET平衡组定义

xml - 为什么 Oxygen 生成具有空 xmlns 属性的子元素?

PHP、XPath 和 SimpleXML - XPath 不起作用

android - 使用 ProgressBar.setProgressDrawable 的问题

python - 单击网页上的隐形按钮(谷歌地图)

html - 使用 Kanna Swift 仅解析来自 HTML 的纯文本

C#-HttpWebRequest-POST

java - Java中如何解析Node并提取子节点的值?

.net - 正则表达式解析任意深度的函数

java - 如何在 Java 中编写 Ruby-regex 模式(包括递归命名分组)?