-
-
Save jbaker6953/deb9a8e4eae1e622f467fc9b4edf11db to your computer and use it in GitHub Desktop.
Updated monkey patch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""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("&", "&").replace("<", "<"). \ | |
replace("\"", """).replace(">", ">") | |
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