Create an XML document
Nis Jørgensen
nis at superlativ.dk
Tue May 22 12:43:45 EDT 2007
kyosohma at gmail.com skrev:
> 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>
> 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.
>From http://wiki.python.org/moin/MiniDom
Add an Element with Text Inside
Create & add an XML element to an XML document, the element has text inside.
ex: <foo>hello, world!</foo>
from xml.dom.minidom import parse
dom = parse("bar.xml")
x = dom.createElement("foo") # creates <foo />
txt = dom.createTextNode("hello, world!") # creates "hello, world!"
x.appendChild(txt) # results in <foo>hello, world!</foo>
dom.childNodes[1].appendChild(x) # appends at end of 1st child's \ children
print dom.toxml()
More information about the Python-list
mailing list