You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

xmlutils.py 1.2KB

12345678910111213141516171819202122232425262728293031323334
  1. """
  2. Utilities for XML generation/parsing.
  3. """
  4. import re
  5. from collections import OrderedDict
  6. from xml.sax.saxutils import XMLGenerator
  7. class UnserializableContentError(ValueError):
  8. pass
  9. class SimplerXMLGenerator(XMLGenerator):
  10. def addQuickElement(self, name, contents=None, attrs=None):
  11. "Convenience method for adding an element with no children"
  12. if attrs is None:
  13. attrs = {}
  14. self.startElement(name, attrs)
  15. if contents is not None:
  16. self.characters(contents)
  17. self.endElement(name)
  18. def characters(self, content):
  19. if content and re.search(r'[\x00-\x08\x0B-\x0C\x0E-\x1F]', content):
  20. # Fail loudly when content has control chars (unsupported in XML 1.0)
  21. # See https://www.w3.org/International/questions/qa-controls
  22. raise UnserializableContentError("Control characters are not supported in XML 1.0")
  23. XMLGenerator.characters(self, content)
  24. def startElement(self, name, attrs):
  25. # Sort attrs for a deterministic output.
  26. sorted_attrs = OrderedDict(sorted(attrs.items())) if attrs else attrs
  27. super().startElement(name, sorted_attrs)