How to retrieve the parent node using cElementTree?

前端 未结 3 1733
鱼传尺愫
鱼传尺愫 2021-01-12 08:44

for the xml


  
     data1
  
  
     data2

        
相关标签:
3条回答
  • 2021-01-12 09:02

    It seems you can get access to the parent from the child using version 1.3 of ElementTree (check http://effbot.org/zone/element-xpath.htm), by using xpath commands like child.find('../parent'). But I think python ships with version 1.2 or something.

    You should also check for lxml which is compatible with etree and has full Xpath support http://lxml.de/

    0 讨论(0)
  • 2021-01-12 09:02

    This syntax seemed to work for cElementTree

    ET.fromstring("<c><a><b></b></a></c>").find('.//b/..')
    

    No going to base parent, and using double slash then single slash in path.
    (would have posted as a comment to above thread but it seems I have no privilege to)

    0 讨论(0)
  • 2021-01-12 09:26
    parent_map = dict((c, p) for p in tree.getiterator() for c in p)
    parent_map[el].remove(el)
    
    0 讨论(0)
提交回复
热议问题