Dealing with xml namespaces with ElementTree

N

Neil Cerutti

I have to parse many xml documents that senselessly(?) specify a
single namespace for the whole document. After a couple of years,
my approach has boiled down to the following three little
helpers, for use with ElementTree:

def insert_namespace(xpath):
# Enable *simple* xpath searches by inserting the fscking namespace.
return '/'.join('{{{}}}{}'.format(XMLNS, n) for n in xpath.split('/'))

def find(et, xpath):
return et.find(insert_namespace(xpath))

def findall(et, xpath):
return et.findall(insert_namespace(xpath))

Instead of writing, e.g.,
et.find('{{0}}ab/{{0}}cd'.format(XMLNS), et al, I can use
find(et, 'ab/cd').

Is there a better ElemenTree based approach I'm missing out on?
And on the other hand, am I circumventing something important, or
inviting bad limitations of some kind?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top