|
14 | 14 | * SAX 2 namespaces |
15 | 15 | """ |
16 | 16 |
|
17 | | -import codecs |
18 | 17 | import io |
19 | 18 | import xml.dom |
20 | 19 |
|
@@ -47,19 +46,22 @@ def toxml(self, encoding=None): |
47 | 46 | return self.toprettyxml("", "", encoding) |
48 | 47 |
|
49 | 48 | def toprettyxml(self, indent="\t", newl="\n", encoding=None): |
50 | | - # indent = the indentation string to prepend, per level |
51 | | - # newl = the newline string to append |
52 | | - use_encoding = "utf-8" if encoding is None else encoding |
53 | | - writer = codecs.getwriter(use_encoding)(io.BytesIO()) |
| 49 | + if encoding is None: |
| 50 | + writer = io.StringIO() |
| 51 | + else: |
| 52 | + writer = io.TextIOWrapper(io.BytesIO(), |
| 53 | + encoding=encoding, |
| 54 | + errors="xmlcharrefreplace", |
| 55 | + newline='\n') |
54 | 56 | if self.nodeType == Node.DOCUMENT_NODE: |
55 | 57 | # Can pass encoding only to document, to put it into XML header |
56 | 58 | self.writexml(writer, "", indent, newl, encoding) |
57 | 59 | else: |
58 | 60 | self.writexml(writer, "", indent, newl) |
59 | 61 | if encoding is None: |
60 | | - return writer.stream.getvalue().decode(use_encoding) |
| 62 | + return writer.getvalue() |
61 | 63 | else: |
62 | | - return writer.stream.getvalue() |
| 64 | + return writer.detach().getvalue() |
63 | 65 |
|
64 | 66 | def hasChildNodes(self): |
65 | 67 | return bool(self.childNodes) |
@@ -1788,12 +1790,12 @@ def importNode(self, node, deep): |
1788 | 1790 | raise xml.dom.NotSupportedErr("cannot import document type nodes") |
1789 | 1791 | return _clone_node(node, deep, self) |
1790 | 1792 |
|
1791 | | - def writexml(self, writer, indent="", addindent="", newl="", |
1792 | | - encoding = None): |
| 1793 | + def writexml(self, writer, indent="", addindent="", newl="", encoding=None): |
1793 | 1794 | if encoding is None: |
1794 | 1795 | writer.write('<?xml version="1.0" ?>'+newl) |
1795 | 1796 | else: |
1796 | | - writer.write('<?xml version="1.0" encoding="%s"?>%s' % (encoding, newl)) |
| 1797 | + writer.write('<?xml version="1.0" encoding="%s"?>%s' % ( |
| 1798 | + encoding, newl)) |
1797 | 1799 | for node in self.childNodes: |
1798 | 1800 | node.writexml(writer, indent, addindent, newl) |
1799 | 1801 |
|
|
0 commit comments