the aim of the code is to insert XML chunks into an XML base structure to create the final XML output.
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import XMLParser
base_tree = ET.parse('base_structure_01.XML')
base_root = base_tree.getroot()
specification = base_tree.find('specification')
applicability = specification.find('applicability')
entity_tree = ET.parse('entity_structure_01.XML')
entity_root = entity_tree.getroot()
ET.indent(entity_root,space =" ",level=3)
applicability.append(entity_root)
base_tree.write('output.xml')
Content of base_structure_01.XML :
<ids>
<specification>
<applicability>
</applicability>
<requirements>
</requirements>
</specification>
</ids>
Content of entity_structure_01.XML :
<entity>
<name>
<simpleValue>name</simpleValue>
</name>
<predefinedtype>
<simpleValue>predefinedtype</simpleValue>
</predefinedtype>
</entity>
What I would like to be the output :
<ids>
<specification>
<applicability>
<entity>
<name>
<simpleValue>name</simpleValue>
</name>
<predefinedtype>
<simpleValue>predefinedtype</simpleValue>
</predefinedtype>
</entity>
</applicability>
<requirements>
</requirements>
</specification>
</ids>
What is currently the output :
<ids>
<specification>
<applicability>
<entity>
<name>
<simpleValue>name</simpleValue>
</name>
<predefinedtype>
<simpleValue>predefinedtype</simpleValue>
</predefinedtype>
</entity></applicability>
<requirements>
</requirements>
</specification>
</ids>
problems :
<entity>
is not correctly indented</entity>
is on the same line as </applicability>
I know there are other options to indent text, I just wanted to know if with the xml.etree.ElementTree it was possible to solve this easily.
Thank you for your time
It works if you apply indent()
on the whole tree, after append()
.
Replace
ET.indent(entity_root,space =" ",level=3)
applicability.append(entity_root)
with this:
applicability.append(entity_root)
ET.indent(base_root,space =" ")