faqts : Computers : Programming : Languages : Python : XML

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

15 of 15 people (100%) answered Yes
Recently 10 of 10 people (100%) answered Yes

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.