3

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'

mzjn
  • 48,958
  • 13
  • 128
  • 248
Golopogus
  • 41
  • 1
  • 2
  • ElementTree does not have a `standalone` option on the `write()` method: https://docs.python.org/3/library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree.write. But lxml does: https://lxml.de/api/lxml.etree._ElementTree-class.html#write – mzjn Jun 17 '21 at 17:41

1 Answers1

3

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()
>>>