Python将xml格式转换为json格式

发布时间:2025-09-01 00:08:11 作者:益华网络 来源:undefined 浏览量(0) 点赞(0)
摘要:在Python编程中,经常遇到xml格式的文件或字符串。由于json格式的方便性,常常希望将xml格式转换为json格式来处理,这可以通过模块xmltodict来实现。 xmltodict模块通过pip来下载和安装: C:\>pip3 install xmltodict

在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格式的字符串。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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

二维码

扫一扫,关注我们

声明:本文由【益华网络】编辑上传发布,转载此文章须经作者同意,并请附上出处【益华网络】及本页链接。如内容、图片有任何版权问题,请联系我们进行处理。

感兴趣吗?

欢迎联系我们,我们愿意为您解答任何有关网站疑难问题!

您身边的【网站建设专家】

搜索千万次不如咨询1次

主营项目:网站建设,手机网站,响应式网站,SEO优化,小程序开发,公众号系统,软件开发等

立即咨询 15368564009
在线客服
嘿,我来帮您!