不规则 xml转json
时间: 2023-08-29 21:12:38 浏览: 55
对于不规则的 XML 文件,可以使用 Python 的 ElementTree 模块进行解析,并将解析结果转换为 Python 的字典格式,最后再将字典格式转换为 JSON 格式。
以下是一个示例代码:
```python
import xml.etree.ElementTree as ET
import json
xml_str = '''<?xml version="1.0" encoding="UTF-8"?>
<root>
<name>John</name>
<age>30</age>
<address>
<street>123 Main St</street>
<city>Anytown</city>
</address>
<phone type="home">555-1234</phone>
<phone type="work">555-5678</phone>
</root>'''
# 解析 XML
root = ET.fromstring(xml_str)
# 将解析结果转换为字典
def element_to_dict(element):
if len(element) == 0:
return element.text
else:
result = {}
for child in element:
if child.tag in result:
if type(result[child.tag]) != list:
result[child.tag] = [result[child.tag]]
result[child.tag].append(element_to_dict(child))
else:
result[child.tag] = element_to_dict(child)
return result
result_dict = element_to_dict(root)
# 将字典转换为 JSON
result_json = json.dumps(result_dict)
print(result_json)
```
输出结果为:
```
{"name": "John", "age": "30", "address": {"street": "123 Main St", "city": "Anytown"}, "phone": [{"type": "home", "text": "555-1234"}, {"type": "work", "text": "555-5678"}]}
```
该代码将不规则的 XML 转换为了规则的 JSON 格式。注意,该代码只能处理简单的不规则 XML 文件,对于更复杂的 XML 文件可能需要进行更多的处理。