将xml格式转换为json格式
在Python编程中,经常遇到xml格式的⽂件或字符串。由于json格式的⽅便性,常常希望将xml格式转换为json格式来处理,这可以通过模
块xmltodict来实现。
xmltodict模块通过pip来下载和安装:
C:\>pip3 install xmltodict
Collecting xmltodict
Downloading
/packages/28/fd/30d5c1d3ac29ce229f6bdc40bbc20b28f716e8b363140c26eff19122d8a5/xmlt 0.12.0-py2.py3-none-any.whl
Installing collected packages: xmltodict
Successfully installed xmltodict-0.12.0
导⼊该模块后,在代码中使⽤xmltodict.parse(xml_str)进⾏处理,这将把xml格式字符串转换为字典格式的数据,再配合json模块的
dumps()函数,将字典转换为json格式的字符串。
import xmltodict
import json
# xml to json
def xmlToJson(xml_str):
try:
json_dict = xmltodict.parse(xml_str, encoding = 'utf-8')
json_str = json.dumps(json_dict, indent = 2)
return json_str
except:
pass
# json to xml
def jsonToXml(json_str):
try:
json_dict = json.loads(json_str)
xml_str = xmltodict.unparse(json_dict, encoding = 'utf-8')
except:
xml_str = xmltodict.umparse({'request':json_dict}, encoding = 'utf-8')
finally:
return xml_str
# load xml file
def load_json(xml_path):
# 获取xml⽂件
xml_file = open(xml_path, 'r')
xml_str = ad()
python处理xml文件# 将读取的xml字符串转换为字典
json_dict = xmltodict.parse(xml_str)
# 将字典转换为json格式的字符串
json_str = json.dumps(json_dict, indent = 2)
return json_str
来⾃ “ ITPUB博客 ” ,链接:blog.itpub/28974745/viewspace-2639062/,如需转载,请注明出处,否则将追究法律
责任。
转载于:blog.itpub/28974745/viewspace-2639062/