Json转xml,包含xml声明
时间: 2023-07-04 14:04:44 浏览: 47
以下是一个Python实现的Json转Xml的示例代码,其中包含了Xml声明:
```python
import json
from xml.etree.ElementTree import Element, SubElement, tostring
def json_to_xml(json_str):
# 将json字符串解析为字典
data = json.loads(json_str)
# 创建根节点
root = Element('root')
# 递归将字典转换为xml元素
def _dict_to_xml(parent, dict_data):
for key, value in dict_data.items():
if isinstance(value, dict):
# 如果值是字典,创建子节点并递归处理
node = SubElement(parent, key)
_dict_to_xml(node, value)
elif isinstance(value, list):
# 如果值是列表,创建子节点并递归处理
for item in value:
node = SubElement(parent, key)
_dict_to_xml(node, item)
else:
# 否则直接创建子节点
node = SubElement(parent, key)
node.text = str(value)
_dict_to_xml(root, data)
# 生成xml字符串,包含xml声明
xml_str = '<?xml version="1.0" encoding="UTF-8"?>\n' + tostring(root, encoding='unicode')
return xml_str
```
使用示例:
```python
json_str = '{"name": "John", "age": 30, "city": "New York", "children": [{"name": "Mary", "age": 5}, {"name": "Tom", "age": 3}]}'
xml_str = json_to_xml(json_str)
print(xml_str)
```
输出结果:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<root>
<name>John</name>
<age>30</age>
<city>New York</city>
<children>
<name>Mary</name>
<age>5</age>
</children>
<children>
<name>Tom</name>
<age>3</age>
</children>
</root>
```