Issues with creating an ElementTree object from scratch to write to an xml file

Viewed 53

I'm working on a project that is currently having me parse some xml files for data and writing that edited data into a specific xml format. I'm also quite new to working with xml files, so bare with me with my lack of vocabulary.

My issue comes in when I am trying to write the new xml file. It is starting from when I write the root of the file as the output file is printing it like this: <root /> when I need it to look like this: <root> </root>

The code that is responsible for writing the output file is:

root = ET.Element('root')
tree = ET.ElementTree()
tree._setroot(root)
for items in dataList:
   temp = ET.Element('element')
   temp.set('attr_1', 'val')
   temp.set('attr_2', 'val')
   temp.set('attr_3', 'val')
   temp.set('attr_4', 'val' + Val)
   temp.set('attr_5', 'val' + items)
   tree.getroot().append(temp)

tree.write('filename', encoding='unicode')

The code inside the for loop isn't super important to the question, since an understanding of the root object will help with getting the rest of this to work, but I included it to show the whole picture. However, to cover my bases, the code within the for loop is supposed to be creating an Element with 5 attributes that are all direct children of the root.

I've been stuck on this file writing for a while, and this was the only code format that I could get to successfully write a new file in the first place. When it comes to file writing and creating an ElementTree object from scratch, I find myself circling around the documentation without finding anything new/helpful. I have also sifted through several sources and websites which all helped me get to this current point, but I'm not able to find anything to help move me forward.

Thank you for reading this and helping me out!

0 Answers
Related