如何在 python 中基于父标签名称在嵌套 xml 中添加新元素

问题描述 投票:0回答:2

我有 config.json 文件,我需要根据配置文件生成 xml 文件

我的配置文件看起来像。

{
"Elements": [
        {
            "Element type": "root",
            "Element name": "root_element"
        },
        {
            "Element type": "sub_element",
            "Parent element": "root_element",
            "Element name": "AAA"
        },
        {
            "Element type": "sub_element",
            "Parent element": "AAA",
            "Element name": "BBB"
        },
        {
            "Element type": "sub_element",
            "Parent element": "BBB",
            "Element name": "CCC"
        },
        {
            "Element type": "sub_element",
            "Parent element": "CCC",
            "Element name": "DDD"
        }
    ]
}

我需要编写 python 代码来生成基于上述文件的嵌套 xml

我试过了,但我没有得到准确的输出

def generate():
    config_path = os.path.join(os.getcwd(), "config", "xml_config.json")
    data = json.load(open(config_path))
    root = None
    for i in data['Elements']:
        if i['Element type'] == 'root':
            root = et.Element(i['Element name'])
        if i['Element type'] == 'sub_element':
            path = root.find(i['Parent element'])
            if path is None:
                et.SubElement(root, i['Element name'])
            else:
                et.SubElement(root.find(i['Parent element']), i['Element name'])
    print(et.tostring(root, encoding='unicode', method='xml'))

我当前的输出如下:

<root_element>
<AAA>
    <BBB />
</AAA>
<CCC />
<DDD />
</root_element>

但我的预期输出是:

<root_element>
   <AAA>
       <BBB>
           <CCC>
               <DDD />
           <CCC />
       </BBB>
   </AAA>
</root_element>
python xml elementtree
2个回答
0
投票

我得到了维护一本字典所需的解决方案。

def generate():
    config_path = os.path.join(os.getcwd(), "config.json")
    data = json.load(open(config_path))
    root = None
    elements_map = {}
    for i in data['Elements']:
        element_type = i['Element type']
        element_name = i['Element name']
        parent_element_name = i.get('Parent element')
        if element_type == 'root':
            root = et.Element(element_name)
            elements_map[element_name] = root
        elif element_type == 'sub_element':
            parent_element = elements_map.get(parent_element_name)
            if parent_element is None:
                raise ValueError(f"Parent element '{parent_element_name}' not found.")
            element = et.SubElement(parent_element, element_name)
            elements_map[element_name] = element
    xml_string = et.tostring(root, encoding='unicode', method='xml')
    print(xml_string)

0
投票

我会这样做:

import json
import xml.etree.ElementTree as ET

obj = json.load(open("config.json"))

elements = {}
elements[root.tag] = ET.Element(obj["Elements"][0]["Element name"])

for el in obj["Elements"][1:]:
    parent = elements[el["Parent element"]]
    elements[el["Element name"]] = ET.SubElement(parent, el["Element name"])

ET.ElementTree(root).write("out.xml", encoding="utf-8", xml_declaration=True)

输出(

out.xml
):

<?xml version="1.0" encoding="UTF-8"?>
<root_element>
   <AAA>
      <BBB>
         <CCC>
            <DDD />
         </CCC>
      </BBB>
   </AAA>
</root_element>
© www.soinside.com 2019 - 2024. All rights reserved.