问题
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