Skip to main content
 首页 » 编程设计

python之如何将 XML 转换为字典

2025年05月04日10soundcode

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

请您参考如下方法:

xmltodict (完全披露:我写的)正是这样做的,遵循这个 "standard" .是Expat -based,所以速度非常快,不需要将整个 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" 
        } 
    } 
}