lxml node comparison
Is there a way to check nodes equal with lxml library? For example in php DOMDocument there is isSameNode
:
a->isSameNode(b) //return b开发者_如何学Pythonoolean
I need it to do something like this:
def find_special_node(special_node, xml):
#iterating nodes in xml
if node == special_node:
return node
You may be able to use xpath to find the item, using attributes of "special_node" as required attributes (and values) in find(). I assume that two nodes are determined to be the same if all attributes of the nodes are the same (such as type, value, size, etc.)
Just a guess
My implementation:
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
Not sure if you want to check NodeA is NodeB
or NodeA == NodeB
You may try:
for node in X.iter():
if node == special_node: # maybe "node is special_node" ?
return node
Anyway, since you already have special_node
, why would you search for it?
精彩评论