Tuesday, February 21, 2012

Using Python minidom module for XML generation

Creating an XML document in Python using the minidom module is quite straightforward.  For simplicity sake, I'll base the code on Hadoop's XML config file.

import sys
from xml.dom.minidom import Document

doc = Document()

configuration = doc.createElement("configuration")

xsl = doc.createProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"configuration.xsl\"")

doc.appendChild(xsl)

prop = doc.createElement("property")

# START LOOP HERE
name = doc.createElement("name")
name_text = doc.createTextNode("my name")
name.appendChild(name_text)

prop.appendChild(name)

value = doc.createElement("value")
value_text = doc.createTextNode("my value")
value.appendChild(value_text)

prop.appendChild(value)
# END LOOP HERE

configuration.appendChild(prop)

doc.appendChild(configuration)

print doc.toprettyxml()

The output is as follows:

<?xml version="1.0" ?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
    <property>
        <name>
            my name
        </name>
        <value>
            my value
        </value>
    </property>
</configuration>

No comments: