在Python编程中,经常遇到xml格式的文件或字符串。由于json格式的方便性,常常希望将xml格式转换为json格式来处理,这可以通过模块xmltodict来实现。
xmltodict模块通过pip来下载和安装:
C:\>pip3 install xmltodict
Collecting xmltodict
Downloading https://files.pythonhosted.org/packages/28/fd/30d5c1d3ac29ce229f6bdc40bbc20b28f716e8b363140c26eff19122d8a5/xmltodict-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 = xml_file.read() # 将读取的xml字符串转换为字典 json_dict = xmltodict.parse(xml_str) # 将字典转换为json格式的字符串 json_str = json.dumps(json_dict, indent = 2) return json_str