I am writing multiple xml files in python by looping over lists of strings. Suppose I have:
from xml.etree.ElementTree import ElementTree, Element, SubElement, tostring
parent = Element('parent')
child = SubElement(parent, 'child')
f = open('file.xml', 'w')
document = ElementTree(parent)
l = ['a', 'b', 'c']
for ch in l:
child.text = ch
document.write(f, encoding='utf-8', xml_declaration=True)
The output:
<?xml version='1.0' encoding='utf-8'?>
<parent><child>a</child></parent><?xml version='1.0' encoding='utf-8'?>
<parent><child>b</child></parent><?xml version='1.0' encoding='utf-8'?>
<parent><child>c</child></parent>
Desired output:
<?xml version='1.0' encoding='utf-8'?>
<parent>
<child>a</child>
<child>b</child>
<child>c</child>
</parent>
I only want the xml declaration to appear one time, at the top of the file. Probably should write the declaration to the file before the loop, but when I attempt that, I get empty elements. I do not want to do this:
f.write('<?xml version='1.0' encoding='utf-8'?>')
How to write just to xml declaration to the file?
Edit: Desired output