将XML转换为python对象的最快方法

时间:2017-05-08 20:53:04

标签: python xml

有没有办法将XML转换为python模型,而不是手动编写解析?

1 个答案:

答案 0 :(得分:2)

尝试xmltodict

  

xmltodict是一个Python模块,它使得使用XML感觉就像使用JSON一样,就像在"spec"中一样:

>>> 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"
        }
    }
}