I am attempting to append elements to an existing .xml using ElementTree.
I have the desired attributes stored as a list of dictionaries:
myDict = [{"name": "dan",
"age": "25",
"subject":"maths"},
{"name": "susan",
"age": "27",
"subject":"english"},
{"name": "leo",
"age": "24",
"subject":"psychology"}]
And I use the following code for the append:
import xml.etree.ElementTree as ET
tree = ET.parse('<path to existing .xml')
root = tree.getroot()
for x,y in enumerate(myDict):
root.append(ET.Element("student", attrib=myDict[x]))
tree.write('<path to .xml>')
This works mostly fine except that all elements are appended as a single line. I'd like to make each element append to be on a new line:
# Not this:
<student name='dan' age='25' subject='maths' /><student name='susan' age='27' subject='english' /><student name='leo' age='24' subject='psychology' />
# But this:
<student name='dan' age='25' subject='maths' />
<student name='susan' age='27' subject='english' />
<student name='leo' age='24' subject='psychology' />
I have attempted use lxml
and pass the pretty_print=True
argument within the tree.write
call but it had no effect.
I'm sure I'm missing something simple here, so your help is appreciated!