d2025cfe5847438541f3a499643906610205d916
[hooke.git] / hooke / compat / minidom.py
1 # Copyright (C) 2010 W. Trevor King <wking@drexel.edu>
2 #
3 # This file is part of Hooke.
4 #
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.
9 #
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.
14 #
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/>.
18
19 """Dynamically patch :mod:`xml.dom.minidom`'s attribute value escaping.
20
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.
24
25 .. _Python bug: http://bugs.python.org/issue5752
26 .. _XML specs:
27   http://www.w3.org/TR/2000/WD-xml-c14n-20000119.html#charescaping
28 """
29
30 import xml.dom.minidom
31
32
33 def _write_data(writer, data, isAttrib=False):
34     "Writes datachars to writer."
35     if isAttrib:
36         data = data.replace("\r", "&#xD;").replace("\n", "&#xA;")
37         data = data.replace("\t", "&#x9;").replace('"', "&quot;")
38     writer.write(data)
39 xml.dom.minidom._write_data = _write_data
40
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)
46
47     attrs = self._get_attributes()
48     a_names = attrs.keys()
49     a_names.sort()
50
51     for a_name in a_names:
52         writer.write(" %s=\"" % a_name)
53         _write_data(writer, attrs[a_name].value, isAttrib=True)
54         writer.write("\"")
55     if self.childNodes:
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))
60     else:
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)