tags:

views:

387

answers:

3

I like the way ElementTree parses xml, in particular the Xpath feature. I've an output in xml from an application with nested tags.

I'd like to access this tags by name without specifying the namespace, is it possible? For example:

root.findall("/molpro/job")

instead of:

root.findall("{http://www.molpro.net/schema/molpro2006}molpro/{http://www.molpro.net/schema/molpro2006}job")
+1  A: 

At least with lxml2, it's possible to reduce this overhead somewhat:

root.findall("/n:molpro/n:job",
             namespaces=dict(n="http://www.molpro.net/schema/molpro2006"))
deets
A: 

You could write your own function to wrap the nasty looking bits for example:

def my_xpath(doc, ns, xp);
    num = xp.count('/')
    new_xp = xp.replace('/', '/{%s}')
    ns_tup = (ns,) * num
    doc.findall(new_xp % ns_tup)

namespace = 'http://www.molpro.net/schema/molpro2006'
my_xpath(root, namespace, '/molpro/job')

Not that much fun I admit but a least you will be able to read your xpath expressions.

Tendayi Mawushe