Lxml.etree and xml.etree.ElementTree adds namespaces without prefixes (ns0, ns1, etc.)

Is there any solution for adding namespaces without a prefix (I mean these ns0, ns1) that work in all etree implementations or are there working solutions for each of them?

Now I have solutions for:

  • lxml - element nsmap argument
  • (c) ElementTree (python 2.6+) - register a namespace method with an empty string as a prefix

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

I think

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

- bad idea?

thanks for the help

+3
3

.

:

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 )

/ :

def writeDown(data, output_filename):

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

, .

+3

Jiri, , :

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)
+1

Python 3.3.1, :

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

, xml.etree.ElementTree._namespace_map, Jiri.

, Python 2.7.4.

0

Source: https://habr.com/ru/post/1780001/


All Articles