Create an XML document

kyosohma at gmail.com kyosohma at gmail.com
Tue May 22 15:35:34 EDT 2007


On May 22, 10:00 am, kyoso... at gmail.com wrote:
> 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

Thanks Nis. Your code worked great. For some reason, Google Groups
seems hosed up today and makes seeing replies impossible on some
posts.

Maximus - What the? You told me to use "createTextNode" and then you
used "doc.createTextElement". I think I know what you mean though.

Thank you both for your advice. It works now.

Mike




More information about the Python-list mailing list