【问题标题】:Is it possible get all context nodes used to evalute xpath result?是否可以获得用于评估 xpath 结果的所有上下文节点?
【发布时间】:2010-01-25 15:58:52
【问题描述】:

是否可以获得用于评估 xpath 结果的所有上下文节点? 在下面的代码中:

test_xml = """
<r>
    <a/>
    <a>
        <b/>
    </a>
    <a>
        <b/>
    </a>
</r>
"""
test_root = lxml.etree.fromstring(test_xml)
res = test_root.xpath("//following-sibling::*[1]/b")
for node in res:
    print test_root.getroottree().getpath(node)

结果是:

/r/a[2]/b
/r/a[3]/b

是否可以获得上述 xpath 评估中使用的所有上下文节点:

/r/a[1] /r/a[2] /r/a[2]/b

第二个结果:

/r/a[2] /r/a[3]/b /r/a[3]/b

? 使用子轴时,我可以让这些节点工作

element_tree.getpath(elem)

但是其他轴呢?

TIA,问候

【问题讨论】:

  • 我不明白您所说的“用于评估 xpath 结果”是什么意思。
  • 当找到结果时,我的意思是每个 xpath 查询级别的上下文节点的序列(按轴分隔)。对于 //following-sibling::*[1]/b 我期望三个节点:1.“根元素”,其中评估开始 2.元素是“根元素”的 follow-sibling::*[1] 3.最后一个是确切的 元素,它是查询的结果
  • 所以本质上您是在尝试获取特定 xml 元素的所有祖先节点?
  • @user258541:您的问题存在概念性问题:开始 // 运算符将扩展为 /descendat-or-self::node()/。这意味着在文档根之后,整个树将被遍历(并且每个节点都将成为下一步的“上下文”节点)。

标签: python xpath lxml


【解决方案1】:

我反转了每个阶段的 xpath 以获得将在结果中评估哪些项目:

for node in res:
    j = node.xpath('./parent::*')[0]
    k = j.xpath('./preceding-sibling::*[1]')[0]
    # You didn't specify these but they were used in the evaluation
    ancestors = k.xpath('./ancestor::*')
    for item in [node, j, k] + ancestors:
        print item.getroottree().getpath(item)
    print '\n\n'

给我:

/r/a[2]/b, /r/a[2], /r/a[1], /r

/r/a[3]/b, /r/a[3], /r/a[2], /r

【讨论】:

    【解决方案2】:

    如果我正确理解了您的问题,那么您正在尝试获取特定节点的祖先节点。 XPATH 表达式为:

    //particular-element/ancestor::*
    

    如:

    /r/a[2]/b/ancestor::*
    

    【讨论】:

      猜你喜欢
      • 2010-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-27
      • 1970-01-01
      • 1970-01-01
      • 2010-10-08
      相关资源
      最近更新 更多