I'm trying to build an XML file using Python with ElementTree, then pretty-printing it using minidom following this snippet. The issue I'm facing is that when I generate a SubElement
, if the string contains quotes, it gets escaped to "
.
The code is pretty simple:
from xml.etree import ElementTree as et
from xml.dom import minidom
def prettify(elem):
"""Return a pretty-printed XML string for the Element."""
rough_string = et.tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent="\t")
top = et.Element("Base")
sub = et.SubElement(top, "Sub")
sub.text = 'Hello this is "a test" with quotes'
print(prettify(top))
And the generated XML is:
<?xml version="1.0" ?>
<Base>
<Sub>Hello this is "a test" with quotes</Sub>
</Base>
Is there a way of avoiding escaping the quotes?