This morning I wrote up a quick tutorial on producing XML with Python. There seems to be many resources on parsing XML in Python, but very few articles/howtos on actually creating it. Here’s the sample code from the first part of this hopefully multipart tutorial:
from xml.dom.minidom import Document
# Create the minidom document
doc = Document()
# Create the <wml> base element
wml = doc.createElement(“wml”)
doc.appendChild(wml)
# Create the main <card> element
maincard = doc.createElement(“card”)
maincard.setAttribute(“id”, “main”)
wml.appendChild(maincard)
# Create a <p> element
paragraph1 = doc.createElement(“p”)
maincard.appendChild(paragraph1)
# Give the <p> elemenet some text
ptext = doc.createTextNode(“This is a test!”)
paragraph1.appendChild(ptext)
# Print our newly created XML
print doc.toprettyxml(indent=” “)
You can find the output of this program and some links in the article. Murphy willing, more will follow.
Update: The code listing should be fixed.