2011-01-20 88 views
1

有沒有辦法檢查與lxml庫相等的節點?例如,在PHP的DOMDocument有isSameNodelxml節點比較

a->isSameNode(b) //return boolean 

我需要做的是這樣的:

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

回答

0

不知道要檢查NodeA is NodeBNodeA == NodeB

你可以試試:

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

無論如何,既然你已經有special_node,你爲什麼要搜索它?

+0

例如,我需要檢查我的'special_node`是否在`xml`中。但無論如何,我需要知道是否有類似於php`isSameNode` – nukl 2011-01-20 08:01:36

1

您可能可以使用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