python - Python 的 ElementTree 是否只允许一个 namespace 映射?

标签 python namespaces elementtree

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

在下面的代码中,我希望第二次查找 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() 使用正确的 namespace 映射?

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

最佳答案

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

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

关于python - Python 的 ElementTree 是否只允许一个 namespace 映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53433051/

相关文章:

PowerShell - 缩短命名空间名称,以便更轻松地访问类型

python,ElementTree,从 xml 文件中添加和删除子元素时出现问题

python - 使用 python 删除 XML 中的子元素

python 将字符串 "0"转换为 float 给出错误

python - 如何沿 X 和 Y 轴缩放图像并裁剪到特定的高度和宽度?

python - VGG16 模型的 OpenCV Python 图像预处理

c++ - 为什么 C++ 参数作用域会影响命名空间内的函数查找?

perl - 如何从 Perl 中的 XML::LibXML 访问属性和元素?

python - 将 elementtree 转储到 xml 文件中

python - 尝试遍历嵌套的 xml 标签,但递归函数未完全深度遍历