如何将XML转换为Dict

ver*_*crp 1 python xml

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

Mar*_*ech 10

xmltodict(完全披露:我写了它)正是这样,遵循这个"标准".它是基于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"
        }
    }
}
Run Code Online (Sandbox Code Playgroud)