lxml etree查找最近的元素b

2024-04-23 23:42:20 发布

您现在位置:Python中文网/ 问答频道 /正文

xml文档的结构如下所示

<a>
    <b>
        <d>
    </b>

    <c attr1="important"/>
    <b>
        <d>
    </b>
    <c attr1="so important" />
    <b></b>
</a>

我的解析器首先获取所有<d>元素

^{pr2}$

现在的任务是:

从当前的<c>标记之前的最近的<c>标记获取属性,如果有的话。

天真的方法是做如下的事情

for el in elems:
    it = el.getparent()
    while it != None and it.tag != 'c':
        prev = it.getprevious()
        if prev == None:
            it = it.getparent()
        else:
            it = prev

    if it != None:
        print el, it.get("attr1")

但对我来说,这看起来并不简单——我是不是遗漏了一些文件?如何在不实现自己的迭代器的情况下解决这个问题?在


Tags: 文档标记none解析器元素ifsoit
1条回答
网友
1楼 · 发布于 2024-04-23 23:42:20

使用^{} axis

The preceding axis indicates all the nodes that precede the context node in the document except any ancestor, attribute and namespace nodes.

for el in elems:
    try:
        print el.xpath("preceding::c[@attr1]")[-1].get("attr1")
    except IndexError:
        print "No preceding 'c' element."

演示:

^{pr2}$

相关问题 更多 >