Document Actions

Creating a new xml document with python (minidom)

by Sérgio Oliveira Campos last modified 2007-09-06 08:57

How to: Create a document; Create a element; Set element's attributes; Append an element on a document; Return a string representing the document; Write the document on a file.



Create a new document using the minidom library is really easy, you need only to import the minidom and after call one method, exactly equals the follow code:

from xml.dom import minidom

# New document
xml = minidom.Document()
Actually the how-to could be finished here, but I will show a little bit more about the minidom.


The next snippet shows how to create an element, set attributes and add this on our document created in the last step.
# Creates user element
userElem = xml.createElement("user")

# Set attributes to user element
userElem.setAttribute("name", "Sergio Oliveira")
userElem.setAttribute("nickname", "seocam")
userElem.setAttribute("email", "seocam@seocam.net")
userElem.setAttribute("photo","seocam.png")

# Append user element in xml document
xml.appendChild(userElem)

If you know the DOM specification nothing until here is new for you, but the next 2 snippets shows how to return a string and how to write a file with our xml document.
# Print the xml code
print xml.toxml("UTF-8")
fp = open("file.xml","w")
xml.writexml(fp, " ", "", "\n", "UTF-8")

# Method's stub
# writexml(self, writer, indent='', addindent='', newl='', encoding=None)

The result generated by both methods:
<?xml version="1.0" encoding="UTF-8"?>
<user email="seocam@seocam.net" name="Sergio Oliveira"
nickname="seocam" photo="seocam.png">


Powered by Plone CMS, the Open Source Content Management System

This site conforms to the following standards: