Dealing with xml namespaces with ElementTree

Discussion in 'Python' started by Neil Cerutti, Jan 21, 2011.

  1. Neil Cerutti

    Neil Cerutti Guest

    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
     
    Neil Cerutti, Jan 21, 2011
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Peter Bengtsson

    ElementTree and namespaces in the header only

    Peter Bengtsson, Jan 15, 2008, in forum: Python
    Replies:
    3
    Views:
    825
    Peter Bengtsson
    Jan 17, 2008
  2. Kee Nethery
    Replies:
    12
    Views:
    2,160
    Stefan Behnel
    Jun 27, 2009
  3. Pete
    Replies:
    2
    Views:
    1,396
  4. Stefan Behnel
    Replies:
    0
    Views:
    818
    Stefan Behnel
    May 4, 2010
  5. Barak, Ron
    Replies:
    1
    Views:
    1,190
    John Machin
    May 5, 2010
Loading...

Share This Page