How to retrieve the parent node using cElementTree?

拟墨画扇 提交于 2019-12-09 03:08:38

问题


for the xml

<grandparent>
  <parent1>
     <child>data1</child>
  </parent1>
  <parent2>
     <child>data2</child>
  </parent2>
</grandparent>

I need the list containing tuples of parent,data for each parent in xml.

Is there a way to do it USING cElementTree? I am able to do it for child,data, but unfortunately child is identical in all the values, hence it is of not much use.


回答1:


parent_map = dict((c, p) for p in tree.getiterator() for c in p)
parent_map[el].remove(el)



回答2:


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/




回答3:


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)



来源:https://stackoverflow.com/questions/374245/how-to-retrieve-the-parent-node-using-celementtree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!