转xml脚本

import xml.etree.ElementTree as ET
import json

def xml_to_dict(element):
    """将 XML 元素转换为字典"""
    if len(element) == 0:  # 如果没有子元素
        return element.attrib  # 返回属性字典
    result = {element.tag: []}
    for child in element:
        child_dict = xml_to_dict(child)
        result[element.tag].append(child_dict)
    return result

# 解析 XML 文件
tree = ET.parse('data.xml')  # 假设你的 XML 文件名为 data.xml
root = tree.getroot()

# 创建一个字典来存储 subject 中的 kk 元素
subject_dict = {}
for kk in root.find('subject').findall('kk'):
    subject_dict[kk.attrib['name']] = {
        'id': kk.attrib['id'],
        'scores': {name.attrib['subject']: name.attrib['score'] for name in kk.findall('name')}
    }

# 将 subject 中的内容合并到 person 中
for entity in root.find('person').findall('entity'):
    name = entity.attrib['name']
    if name in subject_dict:
        entity.attrib.update(subject_dict[name])  # 将 subject 的内容作为属性添加到 entity

# 将合并后的 XML 转换为字典
data_dict = xml_to_dict(root)

# 将字典转换为 JSON
json_data = json.dumps(data_dict, indent=4, ensure_ascii=False)

# 将 JSON 数据写入文件
with open('data.json', 'w', encoding='utf-8') as json_file:
    json_file.write(json_data)

print("XML 文件已成功转换为 JSON 文件。")
posted @ 2024-12-13 10:07  Trkly  阅读(28)  评论(0)    收藏  举报