2005-07-13 09:25:57 +08:00
|
|
|
"""
|
|
|
|
Utilities for XML generation/parsing.
|
|
|
|
"""
|
|
|
|
|
2015-06-19 14:42:48 +08:00
|
|
|
import re
|
2017-02-10 22:29:34 +08:00
|
|
|
from collections import OrderedDict
|
2005-07-13 09:25:57 +08:00
|
|
|
from xml.sax.saxutils import XMLGenerator
|
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2015-06-19 14:42:48 +08:00
|
|
|
class UnserializableContentError(ValueError):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
class SimplerXMLGenerator(XMLGenerator):
|
2006-06-03 21:37:34 +08:00
|
|
|
def addQuickElement(self, name, contents=None, attrs=None):
|
2005-07-13 09:25:57 +08:00
|
|
|
"Convenience method for adding an element with no children"
|
2013-10-17 16:17:41 +08:00
|
|
|
if attrs is None:
|
|
|
|
attrs = {}
|
2005-07-13 09:25:57 +08:00
|
|
|
self.startElement(name, attrs)
|
|
|
|
if contents is not None:
|
|
|
|
self.characters(contents)
|
|
|
|
self.endElement(name)
|
2015-06-19 14:42:48 +08:00
|
|
|
|
|
|
|
def characters(self, content):
|
|
|
|
if content and re.search(r'[\x00-\x08\x0B-\x0C\x0E-\x1F]', content):
|
|
|
|
# Fail loudly when content has control chars (unsupported in XML 1.0)
|
|
|
|
# See http://www.w3.org/International/questions/qa-controls
|
|
|
|
raise UnserializableContentError("Control characters are not supported in XML 1.0")
|
|
|
|
XMLGenerator.characters(self, content)
|
2017-02-10 22:29:34 +08:00
|
|
|
|
|
|
|
def startElement(self, name, attrs):
|
|
|
|
# Sort attrs for a deterministic output.
|
|
|
|
sorted_attrs = OrderedDict(sorted(attrs.items())) if attrs else attrs
|
|
|
|
super().startElement(name, sorted_attrs)
|