xml文件转换json文件的python代码
时间: 2024-02-05 17:03:24 浏览: 85
你可以使用以下Python代码将XML文件转换为JSON文件:
```python
import xmltodict
import json
def convert_xml_to_json(xml_file, json_file):
with open(xml_file, 'r') as f:
xml_str = f.read()
xml_dict = xmltodict.parse(xml_str)
json_str = json.dumps(xml_dict, indent=4)
with open(json_file, 'w') as f:
f.write(json_str)
# 示例用法
convert_xml_to_json('example.xml', 'example.json')
```
在上述代码中,`convert_xml_to_json`函数接受两个参数:`xml_file`是XML文件的路径,`json_file`是要保存JSON文件的路径。函数首先读取XML文件内容,然后使用`xmltodict.parse`将XML字符串转换为字典,再使用`json.dumps`将字典转换为JSON字符串。最后,将JSON字符串写入到指定的JSON文件中。
你可以将上述代码保存到一个Python脚本文件中(例如`xml_to_json.py`),然后运行该脚本即可将XML文件转换为JSON文件。记得将`example.xml`替换为你要转换的实际XML文件的路径,并指定要保存的JSON文件路径(例如`example.json`)。
阅读全文
相关推荐


















