的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