views:

458

answers:

2

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.

A: 
child.xpath('..')

EDIT:

I had in mind something like that:

from cStringIO import StringIO
from lxml import etree

for event, elem in etree.iterparse(StringIO("<a><b></b></a>")):
    print "parent of %s is %s" % (elem, elem.xpath('..'))

Output:

parent of <Element b at b7d060> is [<Element a at b7d030>]
parent of <Element a at b7d030> is []

But apparently it doesn't work for cElementTree that ships with Python.

J.F. Sebastian
child does not have any attribute like xpath in cElementTree
Mohit Ranka
+2  A: 

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://codespeak.net/lxml/

Mapad