lxml.etree和xml.etree.ElementTree如何添加没有前缀的命名空间(ns0, ns1等)

3 投票
3 回答
4989 浏览
提问于 2025-04-16 08:27

有没有办法在不使用前缀的情况下添加命名空间(我指的是那些 ns0、ns1 这样的前缀),而且这个方法能在所有的 etree 实现中都能用,还是说每种实现都有各自的解决方案?

目前我有以下几种解决方案:

  • lxml - 使用 Element 的 nsmap 参数
  • (c)ElementTree(python 2.6 及以上) - 用空字符串作为前缀来注册命名空间的方法

问题在于 (c)ElementTree 在 python 2.5 中,我知道有一个 _namespace_map 属性,但把它设置为空字符串会导致生成无效的 XML,把它设置为 None 又会添加默认的 ns0 等命名空间,请问有没有可行的解决方案?

我想

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

这样做是不是个坏主意?

谢谢你的帮助

3 个回答

0

我正在使用Python 3.3.1,下面的代码对我来说是有效的:

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

好处是你不需要像Jiri建议的那样去访问私有的xml.etree.ElementTree._namespace_map。

我发现Python 2.7.4中也可以使用相同的功能。

1

我用了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)
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)

可能还有更好的解决方案。

撰写回答