# The elementtree.SimpleXMLWriter Module

Tools to write XML files, without having to deal with encoding issues, well-formedness, etc.

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

### Patterns

The following example generates a small XHTML document.

    from elementtree.SimpleXMLWriter import XMLWriter
    import sys

    w = XMLWriter(sys.stdout)

    html = w.start("html")

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

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

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

    w.close(html)

## Module Contents

XMLWriter(file, encoding="us-ascii") (class) [#]

  XML writer class.

  file
    A file or file-like object. This object must implement a write method that takes an 8-bit string.
  encoding
    Optional encoding.

  For more information about this class, see The XMLWriter Class.

## The XMLWriter Class

XMLWriter(file, encoding="us-ascii") (class) [#]

  XML writer class.

  file
    A file or file-like object. This object must implement a write method that takes an 8-bit string.
  encoding
    Optional encoding.
close(id) [#]

  Closes open elements, up to (and including) the element identified by the given identifier.

  id
    Element identifier, as returned by the start method.
comment(comment) [#]

  Adds a comment to the output stream.

  comment
    Comment text, as an 8-bit string or Unicode string.
data(text) [#]

  Adds character data to the output stream.

  text
    Character data, as an 8-bit string or Unicode string.
declaration() [#]

  Writes an XML declaration.

element(tag, text=None, attrib={}, **extra) [#]

  Adds an entire element. This is the same as calling start, data, and end in sequence. The text argument can be omitted.

end(tag=None) [#]

  Closes the current element (opened by the most recent call to start).

  tag
    Element tag. If given, the tag must match the start tag. If omitted, the current element is closed.
flush() [#]

  Flushes the output stream.

start(tag, attrib={}, **extra) [#]

  Opens 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.

  tag
    Element tag.
  attrib
    Attribute dictionary. Alternatively, attributes can be given as keyword arguments.
  Returns:
    An element identifier.