lxml节点比较

2024-10-02 22:25:41 发布

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

有没有一种方法可以检查与lxml库相同的节点?例如,在php DOMDocument中有isSameNode

a->isSameNode(b) //return boolean

我需要它来做这样的事情:

^{pr2}$

Tags: 方法return节点事情lxmlphpbooleanpr2
2条回答

您可以使用xpath查找项,在find()中使用“special_node”属性作为必需的属性(和值)。我假设如果两个节点的所有属性都相同(例如类型、值、大小等),则确定两个节点是相同的
只是一个猜测

我的实现:

import lxml.etree as etree
def isSameNode(a,b,tagsame=True):
    for attrib in a.attrib:
        if a.get(attrib) != b.get(attrib):
            print a.get(attrib),b.get(attrib)
            return False
        else:
            return False
    if a.text != b.text:
        return False
    if tagsame==True:
        if a.tag != b.tag:
            return False
    if a.prefix != b.prefix:
        return False
    if a.tail != b.tail:
        return False
    if a.values()!=b.values(): #may be redundant to the attrib matching
        return False
    if a.keys() != b.keys(): #may also be redundant to the attrib matching
        return False
    return True

def find_alike(xml,special_element,tagsame=True):
    tree = etree.fromstring(xml)
    for node in tree.iter():
        if isSameNode(node,special_element,tagsame):
            return node
    return None

{{cd2>如果你不想检查

您可以尝试:

for node in X.iter():
    if node == special_node: # maybe "node is special_node" ?
        return node

不管怎样,既然已经有special_node,为什么要搜索它?在

相关问题 更多 >