Вы можете использовать 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