【问题标题】:List namespace definitions in an XML document with ElementTree?使用 ElementTree 在 XML 文档中列出命名空间定义?
【发布时间】:2017-03-23 21:28:49
【问题描述】:

如果我有这样的 XML 文件:

<root
 xmlns:a="http://example.com/a"
 xmlns:b="http://example.com/b"
 xmlns:c="http://example.com/c"
 xmlns="http://example.com/base">
   ...
</root>

如何获取命名空间定义的列表(即xmlns:a="…" 等)?

使用:

import xml.etree.ElementTree as ET

tree = ET.parse('foo.xml')
root = tree.getroot()
print root.attrib()

显示一个空的属性字典。

【问题讨论】:

标签: python xml elementtree


【解决方案1】:

通过@mzjn,在 cmets 中,这里是如何使用股票 ElementTree:https://stackoverflow.com/a/42372404/407651

import xml.etree.ElementTree as ET
my_namespaces = dict([
    node for (_, node) in ET.iterparse('file.xml', events=['start-ns'])
])

【讨论】:

    【解决方案2】:

    您可能会发现使用 lxml 更容易。

    from lxml import etree
    xml_data = '<root xmlns:a="http://example.com/a" xmlns:b="http://example.com/b" xmlns:c="http://example.com/c" xmlns="http://example.com/base"></root>'
    
    root_node = etree.fromstring(xml_data)
    print root_node.nsmap
    

    这个输出

    {None: 'http://example.com/base',
    'a': 'http://example.com/a',
    'b': 'http://example.com/b',
    'c': 'http://example.com/c'}
    

    【讨论】:

    • 这不起作用。给我一个空白字段。
    猜你喜欢
    • 1970-01-01
    • 2020-10-17
    • 2018-09-12
    • 1970-01-01
    • 2015-08-02
    • 1970-01-01
    • 2014-09-24
    • 2017-07-08
    • 2011-04-23
    相关资源
    最近更新 更多