Skip to content

Instantly share code, notes, and snippets.

@jbaker6953
Created January 2, 2023 05:54
Show Gist options
  • Save jbaker6953/deb9a8e4eae1e622f467fc9b4edf11db to your computer and use it in GitHub Desktop.
Save jbaker6953/deb9a8e4eae1e622f467fc9b4edf11db to your computer and use it in GitHub Desktop.
Updated monkey patch
"""Dynamically patch :mod:`xml.dom.minidom`'s attribute value escaping.
:meth:`xml.dom.minidom.Element.setAttribute` doesn't preform some
character escaping (see the `Python bug`_ and `XML specs`_).
Importing this module applies the suggested patch dynamically.
.. _Python bug: http://bugs.python.org/issue5752
.. _XML specs:
http://www.w3.org/TR/2000/WD-xml-c14n-20000119.html#charescaping
"""
from xml.dom import Node
import xml.dom.minidom
def _write_data(writer, data, isAttrib=False):
"Writes datachars to writer."
if data:
if isAttrib:
data = data.replace("\r", "
").replace("\n", "
")
data = data.replace("\t", "	")
else: # Otherwise we're overwriting the corrections above
data = data.replace("&", "&amp;").replace("<", "&lt;"). \
replace("\"", "&quot;").replace(">", "&gt;")
writer.write(data)
xml.dom.minidom._write_data = _write_data
def writexml(self, writer, indent="", addindent="", newl=""):
"""Write an XML element to a file-like object
Write the element to the writer object that must provide
a write method (e.g. a file or StringIO object).
"""
# indent = current indentation
# addindent = indentation to add to higher levels
# newl = newline string
writer.write(indent+"<" + self.tagName)
attrs = self._get_attributes()
for a_name in attrs.keys():
writer.write(" %s=\"" % a_name)
_write_data(writer, attrs[a_name].value, isAttrib=True)
writer.write("\"")
if self.childNodes:
writer.write(">")
if (len(self.childNodes) == 1 and
self.childNodes[0].nodeType in (
Node.TEXT_NODE, Node.CDATA_SECTION_NODE)):
self.childNodes[0].writexml(writer, '', '', '')
else:
writer.write(newl)
for node in self.childNodes:
node.writexml(writer, indent+addindent, addindent, newl)
writer.write(indent)
writer.write("</%s>%s" % (self.tagName, newl))
else:
writer.write("/>%s"%(newl))
xml.dom.minidom.Element.writexml = writexml
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment