Python的ElementTree是否只允许一个名称空间映射?

时间:2018-11-22 14:25:33

标签: python namespaces elementtree

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

在下面的代码中,我希望第二次通过barf查找 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位)

1 个答案:

答案 0 :(得分:1)

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

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