从 Python 中的 XML 提取命名空间

Extracting Namespaces from XML in Python

我有类似于以下 XML 文档的内容,名为 sample.xml

<?xml version="1.0" encoding="UTF-8"?>
<package xmlns:test='www.test.com' xmlns:test2='www.test2.com'>
    <test:items>
        <test2:item>Some information</test2:item>
    </test:items>
</package>

我想使用 Python (2.7) 来提取命名空间的字典,如下所示:

>>> import xml.etree.ElementTree as ET
>>> tree = ET.parse('sample.xml')
>>> namespaces = {} # This is the dictionary I want to populate

所需的代码输出:

>>> namespaces 
{'test':'www.test.com', 'test2':'www.test2.com'}

我已经阅读了 ElementTree 的文档,但还没有任何进展。非常感谢任何帮助

如果您将标准库的 xml 换成几乎相同但更强大的 lxml,那么它就像

一样简单
import lxml.etree as ET
tree = ET.parse('sample.xml')
namespaces = tree.nsmap