I have an xml file like this:
<annotation>
<folder>my-project-name</folder>
<filename>red_noisy_snake_0000.png</filename>
<object>
<name>red_noisy_snake</name>
<pose>Unspecified</pose>
<truncated>Unspecified</truncated>
<difficult>Unspecified</difficult>
<bndbox>
<xmin>618</xmin>
<ymin>774</ymin>
<xmax>1037</xmax>
<ymax>858</ymax>
</bndbox>
</object>
</annotation>
And I need to add another 'object' field, similar to the one already present. I have the various values saved in variables (so, 'name', 'pose', 'truncated', the values in 'bndbox'...), and I just need to add it to the original xml file, so that at the end I should end up with something like:
<annotation>
<folder>red_noisy_snake</folder> --> CHANGED VALUE
<filename>red_noisy_snake_0000.png</filename>
<object>
<name>red_noisy_snake</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>618</xmin>
<ymin>774</ymin>
<xmax>1037</xmax>
<ymax>858</ymax>
</bndbox>
</object>
<object> --> ADDED OBJECT FIELD
<name>child_seat</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>871</xmin>
<ymin>25</ymin>
<xmax>1190</xmax>
<ymax>566</ymax>
</bndbox>
</object>
</annotation>
I know how to add a single, non nested element by using for example:
import xml.etree.ElementTree as ET
in_file = 'wrong.xml'
tree = ET.parse(in_file)
root = tree.getroot()
## add single field
add = ET.Element("tag_name")
add.tail = '\n\t'
add.text = 'content'
root.insert(5,add)
ET.dump(root)
but I can't figure out how to properly create the nested structure I need.