I have config.json file i need to generate xml file based on config file
my config file looks like.
{
"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"
}
]
}
I need to write python a code to generate nested xml based above file
I tried but i am not getting exact output
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'))
My current output looks like:
<root_element>
<AAA>
<BBB />
</AAA>
<CCC />
<DDD />
</root_element>
But my expected output is:
<root_element>
<AAA>
<BBB>
<CCC>
<DDD />
<CCC />
</BBB>
</AAA>
</root_element>