Create an XML document

kyosohma at gmail.com kyosohma at gmail.com
Tue May 22 11:00:13 EDT 2007


Hi all,

I am attempting to create an XML document dynamically with Python. It
needs the following format:

<zAppointments reminder="15">
	<appointment>
		<begin>1179775800</begin>
		<duration>1800</duration>
        </appointment>
</zAppointments>

I tried using minidom with the following code:

<code>

from xml.dom.minidom import Document

doc = Document()

zappt = doc.createElement('zAppointments')
zappt.setAttribute('reminder', '15')
doc.appendChild(zappt)

appt = doc.createElement('appointment')
zappt.appendChild(appt)

begin = doc.createElement('begin')
appt.appendChild(begin)
f = file(r'path\to\file.xml', 'w')
f.write(doc.toprettyxml(indent='    '))
f.close()

</code>


This gives me the following:

<?xml version="1.0" ?>
<zAppointments reminder="15">
    <appointment>
        <begin/>
        <duration/>
     </appointment>
</zAppointments>

How do I get Python to put values into the elements by tag name? I can
parse my documents just fine, but now I need to edit them and write
them out to a file for an application I am working on. I am sure I am
missing something obvious.

Thanks a lot!

Mike




More information about the Python-list mailing list