Search code examples
pythonxmlsax

XMLGenerator python sax library: write out inline / closed tag


I write out xml by using the python XMLGenerator class from xml.sax.saxutils.

    xmlwriter = XMLGenerator(output, encoding)
    xmlwriter.startDocument()
    xmlwriter.startElement("foo", {})
    ...
    xmlwriter.endElement("foo", {})

Writing out tags is always done by the startElement and endElement functions. For inline tags (something like XHTML's <br /> or <img />) I would want to write out the tag with end directly. Is there a way to do that with SAX?


Solution

  • If you're using Python 3.2 or later, there's a short_empty_elements parameter you can pass to XMLGenerator (see the Python xml.sax.utils docs).

    For example:

    from xml.sax.saxutils import *
    import sys
    output = sys.stdout
    encoding = 'utf-8'
    xmlwriter = XMLGenerator(output, encoding, short_empty_elements=True)
    xmlwriter.startDocument()
    xmlwriter.startElement(name="foo", attrs={})
    xmlwriter.endElement(name="foo")
    

    will produce the output:

    <?xml version="1.0" encoding="utf-8"?>
    <foo/>