Entry
How can I use a DOM to create an XML document?
Jul 22nd, 2002 09:31
Michael Chermside, Gerhard Haering, Vladimir Cherepanov
First answer: Don't.
Using DOM to output XML documents is probably overkill. The DOM is a
complicated model, and a bit of a pain to use, both because it is
designed to work across all languages, and also just because when you
get down to the details, XML is hard.
But generating XML files isn't so difficult... try something like this:
Python 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> f = file('data.xml', 'w')
>>> f.write('<foo>\n')
>>> f.write(' <bar>Kennigans (great beer on Wed)</bar>\n')
>>> f.write('</foo>\n')
>>> f.close()
Yeah, that's right... all it took was to write text to a file.
Second answer:
It is possible that you are using some of the more esoteric features of
XML, or that you are already manipulating things as DOM trees for some
reason other than creating the file, so you really DO want to create an
XML file using a DOM tree. In that case, the following example should
prove helpful:
>>> from xml.dom.minidom import getDOMImplementation
>>> impl = getDOMImplementation()
>>> doc = impl.createDocument(None, 'foo', None)
>>> root = doc.documentElement
>>> foo = doc.createElement('bar')
>>> root.appendChild(foo)
<DOM Element: foo at 8085320>
>>> f = file('data2.xml', 'w')
>>> doc.writexml(f)
>>> f.close()
Notice that we need to call getDOMImplementation() to get the impl
object which has the createDocument() method.