Convert XML to CSV file

Do not use the findall function, as it will look for att tags in the whole tree. Just iterate the tree in order from top to bottom and grab the relevant elements in them.

from xml.etree import ElementTree
tree = ElementTree.parse('input.xml')
root = tree.getroot()

for att in root:
    first = att.find('attval').text
    for subatt in att.find('children'):
        second = subatt.find('attval').text
        print('{},{}'.format(first, second))

Which gives:

$ python process.py 
Data,Studyval
Data,Site
Info,age
Info,gender

Leave a Comment