【问题标题】:Does Python's ElementTree allow only one namespace mapping?Python 的 ElementTree 是否只允许一个命名空间映射?
【发布时间】:2019-04-25 06:16:08
【问题描述】:

我对 ElementTree 对命名空间映射的命名空间处理感到困惑。我需要解析具有不同默认命名空间的各种树。 ElementTree 似乎保留了我在 find() 中指定的第一个命名空间映射。

在下面的代码中,我希望第二次通过查找 D 时会出错,因为 D 不在传递给 find() 的命名空间中。相反,它确实找到了 D(它有错误的命名空间),但是却在 B(它应该找到)上出现了错误。

try:
    import xml.etree.cElementTree as ET
except ImportError:
    import xml.etree.ElementTree as ET

# Run code for two namespaces
namespaces = [ "http://www.example.org/X", "http://www.example.org/Y"]
for ns in namespaces:
    try:
        # make an XML document as a string
        xmlString='''
            <A xmlns="{ns}" xmlns:static="http://www.example.org/X">
                <B>
                    <C>sam</C>
                </B>
                <static:D>
                    <C>sam</C>
                </static:D>
            </A>
        '''.format(ns=ns)

        print(xmlString)

        tree = ET.fromstring(xmlString)
        # See what namespace is used for the root element
        print("treetag: {}".format(tree.tag))

        # Find the element with the explicit namespace
        elementD = tree.find("ns0:D", { "ns0":ns})
        assert elementD != None, "elementD not found"
        print("elementD: {}".format(elementD.tag))

        # Find the element with the default namespace
        elementB = tree.find("ns0:B", { "ns0":ns})
        assert elementB != None, "elementB not found"
        print("elementB: {}\n".format(elementB.tag))
    except AssertionError as e:
        print repr(e)

我的代码有什么问题吗?如果没有,我如何强制 find() 使用正确的命名空间映射?

环境:Mac OS X、Python 2.7.14 |Anaconda 自定义(64 位)

【问题讨论】:

  • 似乎是 Python 2.7 中未修复的错误。使用 Python 3.7,它会像预期的那样在 D 上发生错误。见bugs.python.org/issue17011
  • 啊,我在搜索中没有找到,谢谢。我很惊讶这个问题被标记为 Python 2.7 的“已修复”,而它显然不是。
  • 是的,该错误已标记为“已修复”。但据我所知,修复只提交给“master”和“3.3”分支。

标签: python namespaces elementtree


【解决方案1】:

您遇到了一个在 Python 3.3 中修复但在 Python 2.7 中未修复的错误:https://bugs.python.org/issue17011(“ElementPath 忽略同一路径表达式的不同命名空间映射”)。

在使用 Python 3.7 时,确实是 D 元素导致了 AssertionError。

【讨论】:

    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 2020-12-26
    • 2012-05-08
    • 2021-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多