Browsing the archives for the Python tag.

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

Python Parse XML Document

Examples

python_logo2

Parsing an XML document in Python is easy. Below is a simple example that loads an XML document from a file, parses and prints:

from xml.dom import minidom
dom = minidom.parse('test.xml')
print dom.toxml()

For more information, see the Python minidom documentation.

1 Comment