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. Advertisements

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. Mark Smits

    Newbie: XML 2 XML and namespaces

    Mark Smits, Sep 17, 2003, in forum: XML
    Replies:
    2
    Views:
    782
    Mark Smits
    Sep 21, 2003
  2. Ultrus
    Replies:
    3
    Views:
    569
    Stefan Behnel
    Jul 9, 2007
  3. Peter Bengtsson

    ElementTree and namespaces in the header only

    Peter Bengtsson, Jan 15, 2008, in forum: Python
    Replies:
    3
    Views:
    980
    Peter Bengtsson
    Jan 17, 2008
  4. Kee Nethery
    Replies:
    12
    Views:
    2,552
    Stefan Behnel
    Jun 27, 2009
  5. Pete
    Replies:
    2
    Views:
    1,580
  6. Barak, Ron
    Replies:
    1
    Views:
    1,869
    John Machin
    May 5, 2010
  7. Terry Reedy
    Replies:
    1
    Views:
    680
    John Machin
    May 5, 2010
  8. Replies:
    4
    Views:
    285
    Stefan Behnel
    Dec 15, 2012
Loading...