virhilo
virhilo

Reputation: 6793

lxml.etree and xml.etree.ElementTree adding namespaces without prefixes(ns0, ns1, etc.)

There is any solution to add namespaces without prefix(i mean these ns0, ns1) which working on all the etree implementations or there are working solutions for each one?

For now I have solutions for:

The problem is (c)ElementTree in python 2.5, I know there is _namespace_map attribute but setting it to empty string creating invalid XML, setting it to None adding default ns0 etc. namespaces, is there any working solution?

I guess

Element('foo', {'xmlns': 'http://my_namespace_url.org/my_ns'})

is a bad idea?

Thanks for help

Upvotes: 3

Views: 5127

Answers (3)

sferencik
sferencik

Reputation: 3249

I'm using Python 3.3.1 and the following works for me:

xml.etree.ElementTree.register_namespace('', 'http://your/uri')
data.write(output_filename)

The upside is that you don't have to access the private xml.etree.ElementTree._namespace_map as Jiri suggested.

I see the same is also available in Python 2.7.4.

Upvotes: 0

Adam Cataldo
Adam Cataldo

Reputation: 722

I used Jiri's idea, but I added an extra line in the case when unique is also the default namespace:

def writeDown(data, output_filename):

    data.write(output_filename)
    txt = file(output_filename).read()
    txt = txt.replace(unique+':','')
    txt = txt.replace('xmlns:'+unique,'xmlns')
    file(output_filename,'w').write(txt)

Upvotes: 1

Jiří Polcar
Jiří Polcar

Reputation: 1222

I have just work around for you.

Define your own prefix:

unique = 'bflmpsvz'

my_namespaces = {
                 'http://www.topografix.com/GPX/1/0' :    unique,
                 'http://www.groundspeak.com/cache/1/0' : 'groundspeak',
                }
xml.etree.ElementTree._namespace_map.update( my_namespaces )

And then, replace/remove the prefix on the output:

def writeDown(data, output_filename):

    data.write(output_filename)
    txt = file(output_filename).read()
    txt = txt.replace(unique+':','')
    file(output_filename,'w').write(txt)

Probably, there is better solution.

Upvotes: 3

Related Questions