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

XML_FILE = '/work/employees.xml'

# read from file to DOM tree
doc = ElementTree.parse(XML_FILE)
# iterate over all employee elements
for employee in doc.getroot().iter('employee'):
    # find attribute no
    no = employee.get('no')
    # find sub elements name and role
    name = employee.find('name').text
    role = employee.find('role').text
    # print
    print('no = %s' % no)
    print('name = %s' % name)
    print('role = %s' % role)
# add employee
newemployee = ElementTree.SubElement(doc.getroot(), 'employee')
newemployee.set('no', '4')
newname = ElementTree.SubElement(newemployee, 'name')
newname.text = 'Dave D'
newrole = ElementTree.SubElement(newemployee, 'role')
newrole.text = 'Intern'
# write out
doc.write('/work/employees2.xml')
