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

孤街醉人 提交于 2019-12-12 09:53:33

问题


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:

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

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


回答1:


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.




回答2:


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)



回答3:


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.



来源:https://stackoverflow.com/questions/4428811/lxml-etree-and-xml-etree-elementtree-adding-namespaces-without-prefixesns0-ns1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!