import xml.etree.ElementTree as ET
import json
import sys

class XMLEngine:
    def __init__(self, config_path):
        self.config_path = config_path

    def load(self):
        tree = ET.parse(self.config_path)
        root = tree.getroot()
        return self._parse_xml(root)

    def _parse_xml(self, element):
        result = {}
        for child in element:
            if len(child) > 0:
                result[child.tag] = self._parse_xml(child)
            else:
                result[child.tag] = child.text
        return result

    def save(self, data):
        root = ET.Element("Configuration")
        self._build_xml(root, data)
        tree = ET.ElementTree(root)
        tree.write(self.config_path, encoding='utf-8', xml_declaration=True)

    def _build_xml(self, parent_element, data):
        for key, value in data.items():
            if isinstance(value, dict):
                child = ET.SubElement(parent_element, key)
                self._build_xml(child, value)
            else:
                child = ET.SubElement(parent_element, key)
                child.text = str(value)

if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("用法: python xml_engine.py {load|save} <文件路径> [<目标文件路径>]")
        sys.exit(1)

    command = sys.argv[1]
    engine = XMLEngine(sys.argv[2])

    if command == "load":
        config_data = engine.load()
        print(json.dumps(config_data, indent=2))
    elif command == "save":
        if len(sys.argv) != 4:
            print("用法: python xml_engine.py save <文件路径> <目标文件路径>")
            sys.exit(1)
        with open(sys.argv[3], 'r') as file:
            data = json.load(file)
        engine.save(data)
    else:
        print("无效的命令")
        sys.exit(1)
