【问题标题】:suppress namespace prefixes in cElementTree抑制 cElementTree 中的命名空间前缀
【发布时间】:2013-09-25 18:35:41
【问题描述】:

在 python 2.6 中,我需要抑制命名空间前缀。我使用了here 发布的解决方案,它可以工作,但是,当我使用 cElementTree 来进行更快的解析时,它会中断。从我的日志中:

25/09/2013 20:04:05 'module' object has no attribute '_namespace_map'

这两种实现之间是否存在一些潜在的差异?还有另一种解决方法吗?我拥有的模块版本:

>>> import xml.etree.ElementTree as et
>>> et.VERSION
'1.2.6'
>>> import xml.etree.cElementTree as cet
>>> cet.VERSION
'1.0.6'
>>> 

谢谢!

【问题讨论】:

  • 您正在挖掘ElementTree 的未记录实现内部结构。 cElementTree 是一个不同的实现,所以它当然不会有相同的内部结构。

标签: python xml elementtree celementtree


【解决方案1】:

没有理由期望这会奏效。 jterrace 在 ElementTree 的内部进行了挖掘,并提出了一个直接作用于这些内部的 hacky woraround。您正在尝试在具有不同内部结构的不同实现中使用它,所以它当然不会起作用。


但是……如果您查看the source to cElementTree,您会发现它处理命名空间注册的方式是……执行一些导入ElementTree 并使用其 命名空间注册的Python 代码。所以,而不是这个:

import xml.etree.cElementTree as etree

# ...

if namespace_uri not in etree._namespace_map:

您可以只导入两者,然后从ElementTree 而不是cElementTree 访问它。例如:

import xml.etree.cElementTree as etree
import xml.etree.ElementTree

# ...

if namespace_uri not in ElementTree._namespace_map:

(显然对它的其他引用做同样的事情。)

不保证这会奏效。它会让你摆脱这个错误,但你必须阅读代码,看看替换 fixtag 是否会对 cElementTree 产生你想要的效果,或者你是否需要做其他事情。

【讨论】:

    猜你喜欢
    • 2011-08-17
    • 2011-12-28
    • 2021-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多