Writing XML with Python xml.minidom

This is an example of how to write XML files with Python2.6 using the xml.minidom light-weight implementation of the Document Object Model interface. Since I had a hard time finding a page showing a simple example, here goes!

# Write XML File (minidom)

 doc = Document()

 root = doc.createElement("User")
 root.setAttribute( "id", 'myIdvalue' )
 root.setAttribute( "email", 'blabla@bblabla.com' )


 for value in XMLvalues:
   # Create Element
   tempChild = doc.createElement(value)

   # Write Text
   nodeText = doc.createTextNode( XMLvalues[value].strip() )

 doc.writexml( open('data.xml', 'w'),
               indent="  ",
               addindent="  ",


This creates an XML file based on a dictionary of values such as:

XMLvalues = { 'a':avalue, 'b':bvalue }

And outputs it pretty enough with decent indentations. Should be self-explanatory, together with the Python Doc page.


One thought on “Writing XML with Python xml.minidom

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s