的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的緩慢,曲柄了很多關於垃圾收集名單,但如果你能處理的,它應該是罰款。
是的:使用lxml,然後您可以遞歸調用elem.getparent()來爬取樹,或者您可以使用elem.xpath('ancestor :: *')並直接獲取祖先節點列表。 (xpath與任何節點一起作爲上下文節點,而不僅僅是文檔根。) – 2010-06-17 18:29:24