Convert XML to CSV file

后端 未结 1 1759
清歌不尽
清歌不尽 2020-12-29 14:43

I have an XML file like this:


    
        1
        

        
1条回答
  •  有刺的猬
    2020-12-29 14:44

    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
    

    0 讨论(0)
提交回复
热议问题