学习资源传送门:https://www.bilibili.com/video/BV1b5411s76z?p=24
(一)学习内容:如何解析简单的xml文档
(二)解决方案
注:现在有 xmltodict 模块,它是一个用来处理xml数据的很方便的模块。包含两个常用方法parse和unparse 。xmltodict
速度非常快(基于 Expat),并且具有内存占用量小的流模式,适用于大型 XML 转储
(1)parse
- xmltodict.parse()方法可以将xml数据转为python中的dict字典数据
(2)unparse
- xmltodict.unparse()方法可以将字典转换为xml字符串
(三)代码
(1)简单尝试
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/12/13 9:24
# @Author : Qiufen.Chen
# @Email : 1760812842@qq.com
# @File : xml_to_dict.py
# @Software: PyCharm
import json
import xmltodict
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))
# output
'''
{
"mydocument": {
"@has": "an attribute",
"and": {
"many": [
"elements",
"more elements"
]
},
"plus": {
"@a": "complex",
"#text": "element as well"
}
}
}
'''
xml_dict = {
"xml": {
"ToUserName": "gh_866835093fea",
"FromUserName": "ogdotwSc_MmEEsJs9-ABZ1QL_4r4",
"CreateTime": "1478317060",
"MsgType": "text",
"Content": u"你好",
"MsgId": "6349323426230210995",
}
}
xml_str = xmltodict.unparse(xml_dict, pretty=True)
print(xml_str)
# output
'''
<?xml version="1.0" encoding="utf-8"?>
<xml>
<ToUserName>gh_866835093fea</ToUserName>
<FromUserName>ogdotwSc_MmEEsJs9-ABZ1QL_4r4</FromUserName>
<CreateTime>1478317060</CreateTime>
<MsgType>text</MsgType>
<Content>你好</Content>
<MsgId>6349323426230210995</MsgId>
</xml>
'''
(2)进阶使用
import xmltodict
def handle_artist(_, artist):
artist['_id'] = artist['name']
print(artist['name'])
return True
fin = r'E:\data\uniprot_sprot.xml.gz'
xmltodict.parse(GzipFile(fin), item_depth=2, item_callback=handle_artist)
————————————————————
参考: