【问题标题】:Extracting Namespaces from XML in Python在 Python 中从 XML 中提取命名空间
【发布时间】:2017-01-11 14:35:26
【问题描述】:

我有类似于以下 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 python-2.7 xml-namespaces elementtree


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-08
      • 1970-01-01
      • 1970-01-01
      • 2016-05-14
      • 1970-01-01
      • 1970-01-01
      • 2021-02-12
      • 2015-07-18
      相关资源
      最近更新 更多