Python Create XML Document

Examples

python_logo2

Creating an XML document in Python can be accomplished by executing:

from xml.dom import minidom
doc = minidom.Document()
testElem = doc.createElement("test")
testElem.setAttribute('id', '1234')
doc.appendChild(testElem)
print doc.toxml()

TheĀ  example above creates an XML document, creates a child element, sets an attribute and then appends the child element to the document.

The XML document in the above example looks like:

<?xml version="1.0" ?><test id="1234"/>
2 Comments

2 Comments

  1. Ariel  •  Sep 9, 2009 @19:20

    There’s something I don’t get about this (maybe because of my lack of experience with Python). Once I’m done appending the Childs how do I actually create the file, I mean the file with its location, written in the hard disk?

    Thanks!

  2. Ryan  •  Sep 9, 2009 @19:26

    The following code is an example of how you write the XML to file:

    f = open(’test.xml’, ‘w’)
    doc.writexml(f)
    f.close()

Leave a Reply

Allowed tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>