How to get parent node using cElementTree?

for xml

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

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

Is there any way to do this USING cElementTree? I can do this for the child, the data, but, unfortunately, the child is identical in all respects, so it is not very useful.

+8
python celementtree
Dec 17 '08 at 11:11
source share
3 answers
 parent_map = dict((c, p) for p in tree.getiterator() for c in p) parent_map[el].remove(el) 
+5
Sep 21 '12 at 15:39
source share

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

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

+4
Dec 17 '08 at 13:46
source share

This syntax seems to work for cElementTree

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

No need to base the parent and use a double slash and then one slash in the path.
(would be posted as a comment on a previous thread, but it seems I have no privileges)

0
Jul 05 '16 at 19:20
source share



All Articles