Writing XML

Starting your script

#!/usr/bin/env python3

# Load minidom
from xml.dom import minidom   

Create an XML document structure

doc = minidom.Document()

Create a tagged element

element = doc.createElement('tag-name')

Set an attribute for an element

element.setAttribute('attrib-name', 'value')

Append a child element to an element

parentElement.appendChild(childElement)

Create a text node element

textElement = doc.createTextNode('text')

Print a document structure as a string

import sys

doc.writexml(sys.stdout, addindent='   ', newl='\n')

Examples

#!/usr/bin/env python3

from xml.dom import minidom
import sys

nspecies = 2
names = ('Felix domesticus', 'Drosophila melanogaster')
commonNames = ('cat', 'fruit fly')
consStatus  = ('not endangered', 'not endangered')

doc = minidom.Document()

data = doc.createElement('data')
doc.appendChild(data)

for i in range(0, nspecies):
    species = doc.createElement('species')
    species.setAttribute('name', names[i])

    data.appendChild(species)

    cname  = doc.createElement('common-name')
    text = doc.createTextNode(commonNames[i])
    cname.appendChild(text)
    species.appendChild(cname)

    cons = doc.createElement('conservation')
    cons.setAttribute('status', consStatus[i])
    species.appendChild(cons)

doc.writexml(sys.stdout, addindent='   ', newl='\n')


[Code]

Continue