用python写一个读取文件中的json文件并且转换成xml格式
时间: 2024-11-27 08:18:48 浏览: 37
在Python中,你可以使用`json`库读取JSON文件,然后使用`xml.etree.ElementTree`模块将数据转化为XML格式。下面是一个简单的示例:
```python
import json
from xml.etree.ElementTree import Element, SubElement, tostring
def json_to_xml(json_data, root_name):
def create_element(element_data, parent):
for key, value in element_data.items():
if isinstance(value, dict):
child = SubElement(parent, key)
json_to_xml(value, child)
else:
SubElement(parent, key).text = str(value)
root = Element(root_name)
json_to_xml(json_data, root)
return tostring(root, encoding='unicode')
# 读取JSON文件
with open('data.json', 'r') as f:
data = json.load(f)
# 将JSON转换为XML
xml_data = json_to_xml(data, 'root')
# 打印或保存到文件
print(xml_data)
```
在这个例子中,你需要先有一个名为'data.json'的JSON文件。这个脚本会读取文件内容,解析成树形结构,然后再按照XML的语法生成一个新的XML文档。
阅读全文