如何将XML转换为Dict

时间:2010-10-04 05:08:42

标签: python xml

我想找到一些很好的解决方案,可以在Python中将XML转换为dict,反之亦然

6 个答案:

答案 0 :(得分:10)

xmltodict(完全披露:我写过)完全按照这个"standard"行事。它基于Expat,所以它非常快,不需要在内存中加载整个XML树。

>>> print(json.dumps(xmltodict.parse("""
...  <mydocument has="an attribute">
...    <and>
...      <many>elements</many>
...      <many>more elements</many>
...    </and>
...    <plus a="complex">
...      element as well
...    </plus>
...  </mydocument>
...  """), indent=4))
{
    "mydocument": {
        "@has": "an attribute", 
        "and": {
            "many": [
                "elements", 
                "more elements"
            ]
        }, 
        "plus": {
            "@a": "complex", 
            "#text": "element as well"
        }
    }
}

答案 1 :(得分:1)

在XML和Python词典之间进行转换时,有一些有趣的极端情况会使这一点变得非常重要(属性?列表?匿名列表?单个条目列表?内容eval?): 从PicklingTools发行版中查看此文档:XML to Dict conversionshttp://www.picklingtools.com

文档讨论了如何做到这一点,但这是一个简单的例子。 在名为“example.xml”的文件中,我们将放置以下XML:

<top>
  <a>1</a>
  <b>2.2</b>
  <c>three</c>
</top>

要处理此文件并将其转换为字典:

>>> from xmlloader import *
>>> example = file('example.xml', 'r')
>>> xl = StreamXMLLoader(example, 0)  # 0 = All defaults on options
>>> result = xl.expectXML()
>>> print result
{'top': {'a': '1', 'c': 'three', 'b': '2.2'}}

答案 2 :(得分:0)

以下食谱应该会有所帮助:

答案 3 :(得分:0)

我可能会建议您查看declxml是否适合您的使用案例(完全披露:我是作者)。使用declxml,可以创建名为 processors 的对象,该对象以声明方式定义XML文档的结构。处理器用于解析XML和Python值,包括对象,字典和命名元组。

import declxml as xml

some_xml = """
<mydocument has="an attribute">
  <and>
    <many>elements</many>
    <many>more elements</many>
  </and>
  <plus a="complex">
    element as well
  </plus>
</mydocument>
"""

processor = xml.dictionary('mydocument', [
    xml.string('.', attribute='has'),
    xml.array(xml.string('many'), nested='and'),
    xml.dictionary('plus', [
        xml.string('.', attribute='a'),
        xml.string('.', alias='plus')
    ])
])

xml.parse_from_string(processor, some_xml)

产生以下输出

{'has': 'an attribute',
 'and': ['elements', 'more elements'],
 'plus': {'a': 'complex', 'plus': 'element as well'}}

答案 4 :(得分:0)

使用func requestRecordPermission(_ response: @escaping PermissionBlock) lib。以下代码片段效果很好:

xmltodict

答案 5 :(得分:-2)

我认为最好的方法是自己动手以满足您的需求。得到lxml,阅读文档,你应该好好去。万一你有疑虑,请马上回来:)。

相关问题