XML writing tools for Python
<p>I'm currently trying ElementTree and it looks fine, it escapes HTML entities and so on and so forth. Am I missing something truly wonderful I haven't heard of?</p>

<p>This is similar to what I'm actually doing:</p>

<pre><code>import xml.etree.ElementTree as ET
root = ET.Element('html')
head = ET.SubElement(root,'head')
script = ET.SubElement(head,'script')
script.set('type','text/javascript')
script.text = "var a = 'I love &amp;aacute; letters'"
body = ET.SubElement(root,'body')
h1 = ET.SubElement(body,'h1')
h1.text = "And I like the fact that 3 &gt; 1"
tree = ET.ElementTree(root)
tree.write('foo.xhtml')

# more foo.xhtml
&lt;html&gt;&lt;head&gt;&lt;script type="text/javascript"&gt;var a = 'I love &amp;amp;aacute;
letters'&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;h1&gt;And I like the fact that 3 &amp;gt; 1&lt;/h1&gt;
&lt;/body&gt;&lt;/html&gt;
</code></pre>

<p>Another way is using the <a href="http://codespeak.net/lxml/tutorial.html#the-e-factory" rel="nofollow">E Factory</a> builder from lxml (available in <a href="http://effbot.org/zone/element-builder.htm" rel="nofollow">Elementtree</a> too)</p>

<pre><code>&gt;&gt;&gt; from lxml import etree

&gt;&gt;&gt; from lxml.builder import E

&gt;&gt;&gt; def CLASS(*args): # class is a reserved word in Python
...     return {"class":' '.join(args)}

&gt;&gt;&gt; html = page = (
...   E.html(       # create an Element called "html"
...     E.head(
...       E.title("This is a sample document")
...     ),
...     E.body(
...       E.h1("Hello!", CLASS("title")),
...       E.p("This is a paragraph with ", E.b("bold"), " text in it!"),
...       E.p("This is another paragraph, with a", "\n      ",
...         E.a("link", href="http://www.python.org"), "."),
...       E.p("Here are some reserved characters: &lt;spam&amp;egg&gt;."),
...       etree.XML("&lt;p&gt;And finally an embedded XHTML fragment.&lt;/p&gt;"),
...     )
...   )
... )

&gt;&gt;&gt; print(etree.tostring(page, pretty_print=True))
&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;This is a sample document&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;h1 class="title"&gt;Hello!&lt;/h1&gt;
    &lt;p&gt;This is a paragraph with &lt;b&gt;bold&lt;/b&gt; text in it!&lt;/p&gt;
    &lt;p&gt;This is another paragraph, with a
      &lt;a href="http://www.python.org"&gt;link&lt;/a&gt;.&lt;/p&gt;
    &lt;p&gt;Here are some reservered characters: &amp;lt;spam&amp;amp;egg&amp;gt;.&lt;/p&gt;
    &lt;p&gt;And finally an embedded XHTML fragment.&lt;/p&gt;
  &lt;/body&gt;
&lt;/html&gt;
</code></pre>
