utilities for xml generationparsing fail loudly when content has control chars unsupported in xml 1 0 see https www w3 orginternationalquestionsqacontrols sort attrs for a deterministic output fail loudly when content has control chars unsupported in xml 1 0 see https www w3 org international questions qa controls sort attrs for a deterministic output
import re
from xml.sax.saxutils import XMLGenerator


class UnserializableContentError(ValueError):
    pass


class SimplerXMLGenerator(XMLGenerator):
    def addQuickElement(self, name, contents=None, attrs=None):
        "Convenience method for adding an element with no children"
        if attrs is None:
            attrs = {}
        self.startElement(name, attrs)
        if contents is not None:
            self.characters(contents)
        self.endElement(name)

    def characters(self, content):
        if content and re.search(r"[\x00-\x08\x0B-\x0C\x0E-\x1F]", content):
            
            
            raise UnserializableContentError(
                "Control characters are not supported in XML 1.0"
            )
        XMLGenerator.characters(self, content)

    def startElement(self, name, attrs):
        
        sorted_attrs = dict(sorted(attrs.items())) if attrs else attrs
        super().startElement(name, sorted_attrs)