1 # Copyright (C) 2010 W. Trevor King <wking@drexel.edu>
3 # This file is part of Hooke.
5 # Hooke is free software: you can redistribute it and/or modify it
6 # under the terms of the GNU Lesser General Public License as
7 # published by the Free Software Foundation, either version 3 of the
8 # License, or (at your option) any later version.
10 # Hooke is distributed in the hope that it will be useful, but WITHOUT
11 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
13 # Public License for more details.
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with Hooke. If not, see
17 # <http://www.gnu.org/licenses/>.
19 """Dynamically patch :mod:`xml.dom.minidom`'s attribute value escaping.
21 :meth:`xml.dom.minidom.Element.setAttribute` doesn't preform some
22 character escaping (see the `Python bug`_ and `XML specs`_).
23 Importing this module applies the suggested patch dynamically.
25 .. _Python bug: http://bugs.python.org/issue5752
27 http://www.w3.org/TR/2000/WD-xml-c14n-20000119.html#charescaping
30 import xml.dom.minidom
33 def _write_data(writer, data, isAttrib=False):
34 "Writes datachars to writer."
36 data = data.replace("\r", "
").replace("\n", "
")
37 data = data.replace("\t", "	").replace('"', """)
39 xml.dom.minidom._write_data = _write_data
41 def writexml(self, writer, indent="", addindent="", newl=""):
42 # indent = current indentation
43 # addindent = indentation to add to higher levels
44 # newl = newline string
45 writer.write(indent+"<" + self.tagName)
47 attrs = self._get_attributes()
48 a_names = attrs.keys()
51 for a_name in a_names:
52 writer.write(" %s=\"" % a_name)
53 _write_data(writer, attrs[a_name].value, isAttrib=True)
56 writer.write(">%s"%(newl))
57 for node in self.childNodes:
58 node.writexml(writer,indent+addindent,addindent,newl)
59 writer.write("%s</%s>%s" % (indent,self.tagName,newl))
61 writer.write("/>%s"%(newl))
62 # For an introduction to overriding instance methods, see
63 # http://irrepupavel.com/documents/python/instancemethod/
64 instancemethod = type(xml.dom.minidom.Element.writexml)
65 xml.dom.minidom.Element.writexml = instancemethod(
66 writexml, None, xml.dom.minidom.Element)