将json转换为xml文件的代码怎么写
时间: 2023-06-05 21:08:51 浏览: 123
以下是将json转换为xml文件的Python代码:
```python
import json
import xml.etree.ElementTree as ET
def json_to_xml(json_string, root_name):
# 将json字符串转换为字典
json_dict = json.loads(json_string)
# 创建XML根节点
root_elem = ET.Element(root_name)
# 将json字典转换为XML元素
for key in json_dict:
child_elem = ET.SubElement(root_elem, key)
child_elem.text = str(json_dict[key])
# 将XML根节点输出为字符串
xml_string = ET.tostring(root_elem, encoding='unicode')
return xml_string
```
使用示例:
```python
# 将JSON字符串转换为XML文件
json_string = '{"name": "John", "age": 30}'
root_name = 'person'
xml_string = json_to_xml(json_string, root_name)
# 将XML字符串写入文件
with open('person.xml', 'w') as f:
f.write(xml_string)
```
运行上面的代码后,会生成一个名为`person.xml`的文件,其内容如下:
```xml
<?xml version='1.0' encoding='unicode'?>
<person>
<name>John</name>
<age>30</age>
</person>
```
阅读全文