I have two folders in which one folder contains thousands of images and another folder has corresponding .xml files. XML file and image names are same (i.e. 2007.xml and 2007.jpg). Now i would like to add image name (2007.jpg) into their corresponding file (2007.xml). .xml file format is:
<?xml version='1.0' encoding='ASCII'?>
<annotation>
<size>
<width>1820</width>
<height>940</height>
</size>
<object>
<name>Car</name>
<bndbox>
<xmin>74.0</xmin>
<ymin>509.0</ymin>
<xmax>236.0</xmax>
<ymax>609.0</ymax>
</bndbox>
</annotation>
i want to add new SubElement
<?xml version='1.0' encoding='ASCII'?>
<annotation>
<filename>2007.jpg</filename>
<size>
<width>1820</width>
<height>940</height>
</size>
<object>
<name>Car</name>
<bndbox>
<xmin>74.0</xmin>
<ymin>509.0</ymin>
<xmax>236.0</xmax>
<ymax>609.0</ymax>
</bndbox>
</annotation>
I am trying this way:
import xml.etree.ElementTree as ET
import os
doc = ET.parse('00390.xml')
root = doc.getroot()
s = '/image/00390.jpg'
filename = (os.path.basename(s))
userElement = ET.Element("annotation")
newSub = ET.SubElement(userElement, "filename")
newSub.set(filename, '')
root.insert(0, newSub)
tree = ET.ElementTree(root)
tree.write(open('3.xml', 'w'), encoding = 'UTF-8')
Output is received: <filename 00390.jpg=""/>
Although output should be <filename>00390.jpg</filename>
I think issue is using newSub.set() which takes 3 input argument.
insert()which takes an index: docs.python.org/3/library/…. Similar question: stackoverflow.com/q/25824920/407651