2010-06-14 78 views

回答

1

的ElementTree(V1.3或更高版本)的最新版本,你可以簡單地做

input_element.find('..') 

遞歸。然而,Python附帶的ElementTree沒有這個功能,而且在Element類中看不到任何東西。

我相信這意味着你必須這麼做:通過對元素樹的詳盡搜索。

def get_ancestors_recursively(e, b): 
    "Finds ancestors of b in the element tree e." 
    return _get_ancestors_recursively(e.getroot(), b, []) 

def _get_ancestors_recursively(s, b, acc): 
    "Recursive variant. acc is the built-up list of ancestors so far." 
    if s == b: 
     return acc 
    else: 
     for child in s.getchildren(): 
      newacc = acc[:] 
      newacc.append(s) 
      res = _get_ancestors_recursively(child, b, newacc) 
      if res is not None: 
       return res 
     return None 

這是因爲DFS的緩慢,曲柄了很多關於垃圾收集名單,但如果你能處理的,它應該是罰款。

2

另一個選項是LXML,它爲內置的ElementTree api提供了有用的擴展。如果你願意安裝一個外部模塊,它有一個不錯的Element.getparent()函數,你可以簡單地調用,直到達到ElementTree.getroot()。這可能是最快和最優雅的解決方案(因爲lxml.etree module引入了指向它們父項的元素的指針屬性,所以不是在整個樹中搜索適當的parent/child對)。

+0

是的:使用lxml,然後您可以遞歸調用elem.getparent()來爬取樹,或者您可以使用elem.xpath('ancestor :: *')並直接獲取祖先節點列表。 (xpath與任何節點一起作爲上下文節點,而不僅僅是文檔根。) – 2010-06-17 18:29:24

0

找到這個小寶石從大量使用Google(http://elmpowered.skawaii.net/?p=74

父= root.findall( 「.// {0}/..」。格式(elem.tag))

根這裏的是樹的根節點。 elem是您從迭代中獲得的實際元素對象。

這確實需要你知道根,這可能意味着改變你爲XML解析設置的方式,但它最好是最小的。

相關問題