Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve the parent node using cElementTree?

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.

like image 377
Mohit Ranka Avatar asked Dec 17 '08 11:12

Mohit Ranka


People also ask

How do I get Parent nodes in Python?

Find node's parent using the path: parent_node = node. find('..')

How do you check if a node has a parent?

The parent of each node is found by accessing the parentNode property which returns the parent node if any. A while loop is used until the parent required is found or no more parent elements exist. Inside this loop, each element's parent node is found in every iteration.


1 Answers

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/

like image 153
Mapad Avatar answered Oct 05 '22 01:10

Mapad