If your program needs to write some output as an XML
document, the lxml package makes this operation easy.
First import the lxml package. Here is one way:
from lxml import etree
Create the root element. For example, suppose you're
creating a Web page; the root element is html. Use the etree.Element()
constructor to build that element.
page = etree.Element ( 'html' )
Next, use the etree.ElementTree()
constructor to make a new document tree, using our
html element as its root:
doc = etree.ElementTree ( page )
The etree.SubElement() constructor is
perfect for adding new child elements to our document.
Here's the code to add a head element,
and then a body as element, as new
children of the html element:
headElt = etree.SubElement ( page, 'head' ) bodyElt = etree.SubElement ( page, 'body' )
Your page will need a title element
child under the head element. Add text
to this element by storing a string in its .text attribute:
title = etree.SubElement ( headElt, 'title' ) title.text = 'Your page title here'
To supply attribute values, use keyword arguments to
the SubElement() constructor. For
example, suppose you want a stylesheet link inside the
head element that looks like this:
<link rel='stylesheet' href='mystyle.css' type='text/css'>
This code would do it:
linkElt = etree.SubElement ( headElt, 'link', rel='stylesheet',
href='mystyle.css', type='text/css' )
Continue building your new document using the various
functions described in Section 6, “Features of the etree module”
and Section 8, “class Element: One element in the tree”.
When the document is completely built, write it to a
file using the ElementTree instance's
.write() method, which takes a file argument.
outFile = open ( 'homemade.xml' ) doc.write ( outFile )