Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Dealing with xml namespaces with ElementTree

Thread Tools

Dealing with xml namespaces with ElementTree

Neil Cerutti
Posts: n/a
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?

Neil Cerutti
Reply With Quote

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
RE: How to get xml.etree.ElementTree not bomb on invalid charactersin XML file ? Barak, Ron Python 1 05-05-2010 12:37 AM
Re: How to get xml.etree.ElementTree not bomb on invalid charactersin XML file ? Stefan Behnel Python 0 05-04-2010 07:23 AM
Ignoring XML Namespaces with ElementTree Pete Python 2 12-03-2009 09:39 PM
ElementTree.XML(string XML) and ElementTree.fromstring(string XML)not working Kee Nethery Python 12 06-27-2009 06:06 AM
ElementTree and namespaces in the header only Peter Bengtsson Python 3 01-17-2008 12:13 AM