python xml转json
时间: 2023-08-29 10:13:06 浏览: 47
可以使用Python的xmltodict和json库将XML转换为JSON。
首先,安装xmltodict库:
```
pip install xmltodict
```
然后,使用以下代码将XML转换为JSON:
```python
import xmltodict
import json
with open('example.xml') as xml_file:
data_dict = xmltodict.parse(xml_file.read())
json_data = json.dumps(data_dict)
print(json_data)
```
其中,'example.xml'是要转换的XML文件名。将XML文件读取为字符串,然后使用xmltodict.parse()将其转换为Python字典。最后,使用json.dumps()将字典转换为JSON字符串。
相关问题
Python xml转json
可以使用 Python 内置的 `xml.etree.ElementTree` 模块和 `json` 模块来实现 xml 转换为 json。
下面是一个简单的示例代码:
``` python
import xml.etree.ElementTree as ET
import json
# 读取 xml 文件
tree = ET.parse('sample.xml')
root = tree.getroot()
# 将 xml 转换为字典
xml_dict = {}
for child in root:
xml_dict[child.tag] = child.text
# 将字典转换为 json
json_data = json.dumps(xml_dict)
print(json_data)
```
这个示例代码假设 xml 文件的结构类似于:
``` xml
<root>
<name>John</name>
<age>30</age>
<gender>Male</gender>
</root>
```
如果 xml 文件的结构更加复杂,那么需要针对具体的情况做出相应的修改。
python json转xml格式
你可以使用 Python 的 `xml.etree.ElementTree` 模块来将 JSON 格式转换为 XML 格式。具体步骤如下:
1. 首先,将 JSON 格式转换为 Python 的字典或列表对象。可以使用 `json.loads()` 函数来实现。
```python
import json
json_str = '{"name": "Alice", "age": 20, "hobbies": ["reading", "traveling"]}'
data = json.loads(json_str)
```
2. 然后,使用 `xml.etree.ElementTree` 模块创建根元素,并递归地将字典或列表转换为 XML 元素。
```python
import xml.etree.ElementTree as ET
def json_to_xml(data):
root = ET.Element("root")
if isinstance(data, dict):
for key, value in data.items():
child = ET.Element(key)
root.append(child)
json_to_xml(value, child)
elif isinstance(data, list):
for item in data:
child = ET.Element("item")
root.append(child)
json_to_xml(item, child)
else:
root.text = str(data)
return root
```
3. 最后,使用 `ET.tostring()` 函数将根元素转换为 XML 字符串。
```python
xml_str = ET.tostring(json_to_xml(data))
print(xml_str)
```
完整代码如下:
```python
import json
import xml.etree.ElementTree as ET
def json_to_xml(data):
root = ET.Element("root")
if isinstance(data, dict):
for key, value in data.items():
child = ET.Element(key)
root.append(child)
json_to_xml(value, child)
elif isinstance(data, list):
for item in data:
child = ET.Element("item")
root.append(child)
json_to_xml(item, child)
else:
root.text = str(data)
return root
json_str = '{"name": "Alice", "age": 20, "hobbies": ["reading", "traveling"]}'
data = json.loads(json_str)
xml_str = ET.tostring(json_to_xml(data))
print(xml_str)
```