Reputation: 41
I've tried looking at other questions similar to this, but none seem to answer for xml.etree.ElementTree.
Currently my code looks like this (it's just a simple XML generator)
import xml.etree.ElementTree as ET
example1=ET.Element('example1')
example2=ET.SubElement(example1, 'example2').text='1234'
tree = ET.ElementTree(example1)
NewXML='example.xml'
tree.write(NewXML,encoding = 'UTF-8', xml_declaration = True)
Currently the output is simply this file:
<?xml version='1.0' encoding='UTF-8'?>
<example1>
<example2>1234</example2>
</example1>
I want to add the declaration standalone = 'yes' so the output should be:
<?xml version='1.0' encoding='UTF-8' standalone = 'yes'?>
<example1>
<example2>1234</example2>
</example1>
However that's where I'm running into issues.
I've tried
tree.write(NewXML,encoding = "UTF-8", xml_declaration = True, standalone = True)
tree.write(NewXML,encoding = "UTF-8", xml_declaration = True, standalone = "yes")
but I get this error: TypeError: write() got an unexpected keyword argument 'standalone'
Upvotes: 3
Views: 3972
Reputation:
How about writing the declaration yourself?
>>> import xml.etree.ElementTree as ET
>>> example1=ET.Element('example1')
>>> example2=ET.SubElement(example1, 'example2').text='1234'
>>> tree = ET.ElementTree(example1)
>>> NewXML='example.xml'
>>> out = open(NewXML, 'wb')
>>> out.write(b'<?xml version="1.0" encoding="UTF-8" standalone = "yes"?>\n')
58
>>> tree.write(out, encoding = 'UTF-8', xml_declaration = False)
>>> out.close()
>>>
Upvotes: 3