d3bdfac39f2bc6eb0dac950849e98b847c6f04064f3b68304ad69f0d3380375f866bb6853a6422fe508aa9b7e66fc536800a0b0728622e801f10da0c4efed2 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # Copyright (c) 2011 Google Inc. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. """Applies a fix to CR LF TAB handling in xml.dom.
  5. Fixes this: http://code.google.com/p/chromium/issues/detail?id=76293
  6. Working around this: http://bugs.python.org/issue5752
  7. TODO(bradnelson): Consider dropping this when we drop XP support.
  8. """
  9. import xml.dom.minidom
  10. def _Replacement_write_data(writer, data, is_attrib=False):
  11. """Writes datachars to writer."""
  12. data = data.replace("&", "&amp;").replace("<", "&lt;")
  13. data = data.replace('"', "&quot;").replace(">", "&gt;")
  14. if is_attrib:
  15. data = data.replace("\r", "&#xD;").replace("\n", "&#xA;").replace("\t", "&#x9;")
  16. writer.write(data)
  17. def _Replacement_writexml(self, writer, indent="", addindent="", newl=""):
  18. # indent = current indentation
  19. # addindent = indentation to add to higher levels
  20. # newl = newline string
  21. writer.write(indent + "<" + self.tagName)
  22. attrs = self._get_attributes()
  23. a_names = sorted(attrs.keys())
  24. for a_name in a_names:
  25. writer.write(' %s="' % a_name)
  26. _Replacement_write_data(writer, attrs[a_name].value, is_attrib=True)
  27. writer.write('"')
  28. if self.childNodes:
  29. writer.write(">%s" % newl)
  30. for node in self.childNodes:
  31. node.writexml(writer, indent + addindent, addindent, newl)
  32. writer.write(f"{indent}</{self.tagName}>{newl}")
  33. else:
  34. writer.write("/>%s" % newl)
  35. class XmlFix:
  36. """Object to manage temporary patching of xml.dom.minidom."""
  37. def __init__(self):
  38. # Preserve current xml.dom.minidom functions.
  39. self.write_data = xml.dom.minidom._write_data
  40. self.writexml = xml.dom.minidom.Element.writexml
  41. # Inject replacement versions of a function and a method.
  42. xml.dom.minidom._write_data = _Replacement_write_data
  43. xml.dom.minidom.Element.writexml = _Replacement_writexml
  44. def Cleanup(self):
  45. if self.write_data:
  46. xml.dom.minidom._write_data = self.write_data
  47. xml.dom.minidom.Element.writexml = self.writexml
  48. self.write_data = None
  49. def __del__(self):
  50. self.Cleanup()