XML writing tools for Python XML writing tools for Python python python

XML writing tools for Python


Another way is using the E Factory builder from lxml (available in Elementtree too)

>>> from lxml import etree>>> from lxml.builder import E>>> def CLASS(*args): # class is a reserved word in Python...     return {"class":' '.join(args)}>>> 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: <spam&egg>."),...       etree.XML("<p>And finally an embedded XHTML fragment.</p>"),...     )...   )... )>>> print(etree.tostring(page, pretty_print=True))<html>  <head>    <title>This is a sample document</title>  </head>  <body>    <h1 class="title">Hello!</h1>    <p>This is a paragraph with <b>bold</b> text in it!</p>    <p>This is another paragraph, with a      <a href="http://www.python.org">link</a>.</p>    <p>Here are some reservered characters: <spam&egg>.</p>    <p>And finally an embedded XHTML fragment.</p>  </body></html>


There's always SimpleXMLWriter, part of the ElementTree toolkit. The interface is dead simple.

Here's an example:

from elementtree.SimpleXMLWriter import XMLWriterimport sysw = 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)


I assume that you're actually creating an XML DOM tree, because you want to validate that what goes into this file is valid XML, since otherwise you'd just write a static string to a file. If validating your output is indeed your goal, then I'd suggest

from xml.dom.minidom import parseStringdoc = parseString("""<html>    <head>        <script type="text/javascript">            var a = 'I love &aacute; letters'        </script>    </head>    <body>        <h1>And I like the fact that 3 > 1</h1>    </body>    </html>""")with open("foo.xhtml", "w") as f:    f.write( doc.toxml() )

This lets you just write the XML you want to output, validate that it's correct (since parseString will raise an exception if it's invalid) and have your code look much nicer.

Presumably you're not just writing the same static XML every time and want some substitution. In this case I'd have lines like

var a = '%(message)s'

and then use the % operator to do the substitution, like

</html>""" % {"message": "I love &aacute; letters"})