# Collection of code snippets by Arne Vajhøj 
# (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
from xml.dom.minidom import parse
from xml.dom import Node

XML_FILE = '/work/employees.xml'

# read from file to DOM tree
doc = parse(XML_FILE)
# iterate over all employee elements
employees = doc.getElementsByTagName('employee')
for employee in employees:
    # find attribute no
    no = employee.getAttribute('no')
    # find sub elements name and role
    name = ''
    role = ''
    children = employee.childNodes
    for child in children:
        if child.nodeType == Node.ELEMENT_NODE:
            if child.nodeName == 'name':
                name = child.firstChild.nodeValue
            if child.nodeName == 'role':
                role = child.firstChild.nodeValue
    # print
    print('no = %s' % no)
    print('name = %s' % name)
    print('role = %s' % role)
# add employee
newname = doc.createElement('name')
newname.appendChild(doc.createTextNode('Dave D'))
newrole = doc.createElement('role')
newrole.appendChild(doc.createTextNode('Intern'))
newemployee = doc.createElement('employee')
newemployee.setAttribute('no', '4')
newemployee.appendChild(newname)
newemployee.appendChild(newrole)
doc.documentElement.appendChild(newemployee)
# write out
doc.writexml(open('/work/employees2.xml', 'w'), '', '    ', '\n')
