2010-06-14 79 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解析设置的方式,但它最好是最小的。

相关问题