lxml.etree和xml.etree.ElementTree添加不带前缀的名称空间(ns0,ns1等) [英] lxml.etree and xml.etree.ElementTree adding namespaces without prefixes(ns0, ns1, etc.)
问题描述
有什么解决方案可以添加不带前缀的名称空间(我的意思是这些ns0,ns1),该名称空间适用于所有etree实现,或者每个解决方案都有有效的解决方案?
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参数
- (c)ElementTree (python 2.6+)-使用空字符串作为前缀注册名称空间方法
- lxml - nsmap argument of Element
- (c)ElementTree(python 2.6+) - register namespace method with empty string as a prefix
问题是python 2.5中的(c)ElementTree,我知道有_namespace_map属性,但是将其设置为空字符串会创建无效的XML,将其设置为None会添加默认的ns0等名称空间,是否有任何可行的解决方案?
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?
我猜
Element('foo', {'xmlns': 'http://my_namespace_url.org/my_ns'})
是个坏主意吗?
感谢帮助
推荐答案
我为您工作了.
定义您自己的前缀:
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.
这篇关于lxml.etree和xml.etree.ElementTree添加不带前缀的名称空间(ns0,ns1等)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!