gpt4 book ai didi

python - lxml节点比较

转载 作者:太空宇宙 更新时间:2023-11-03 19:33:15 35 4
gpt4 key购买 nike

有没有办法检查节点是否与 lxml 库相同?例如在 php DOMDocument 中有 isSameNode:

a->isSameNode(b) //return boolean

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

def find_special_node(special_node, xml):
#iterating nodes in xml
if node == special_node:
return node

最佳答案

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

我的实现:

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

关于python - lxml节点比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4744401/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com