Updated October 3, 2004 | Fredrik Lundh

The SimpleXMLWriter module contains a simple helper class for applications that need to generate well-formed XML data.

The current version does not provide built-in support for namespaces. To create files using namespaces, you currently have to provide “xmlns” attributes and explicitly add prefixes to tags and attributes.


writer = SimpleXMLWriter.XMLWriter(file, encoding). Create a writer object. The encoding defaults to “us-ascii”, but can also be set to “utf-8”. You can use other encodings, but in such cases, you must write the XML header yourself.

writer.start(tag, attributes…) => id. Open a new element. Attributes can be given as keyword arguments, or as a string/string dictionary. You can pass in 8-bit strings or Unicode strings; the former are assumed to use the encoding passed to the constructor. The method returns an opaque identifier that can be passed to the close method to close all open elements up to and including this one. Add text content to the current element. You can pass in 8-bit strings or Unicode strings; see above for details.

writer.end(). Close current element (opened by the most recent call to start).

writer.end(tag). Close current element. The tag must match the current element tag.

writer.element(tag, text, attributes…). Add an entire element. This is the same as calling start, data, and end in sequence. The text argument can be omitted.

writer.close(id). Close open elements, up to (and including) the element identified by the given identifier. Identifiers are returned by the start method.

writer.close(). Close all open elements.


The following snippet generates a small XHTML document.

from elementtree.SimpleXMLWriter import XMLWriter
import sys

w = XMLWriter(sys.stdout)

html = w.start("html")

w.element("title", "my document")
w.element("meta", name="generator", value="my application 1.0")

w.element("h1", "this is a heading")
w.element("p", "this is a paragraph")

w.start("p")"this is ")
w.element("b", "bold")" and ")
w.element("i", "italic")".")



The SimpleXMLWriter module is shipped with the ElementTree toolkit. You can get the toolkit from the downloads page.


A Django site. rendered by a django application. hosted by webfaction.