Good day. It is necessary to parse xml and write to csv in python of the following form:

<Root> <SubRoot> <Level1>A</Level1> <Level2>B</Level2> <Level3>C</Level3> <Level4>D</Level4> </SubRoot> <SubRoot> <Level1>1</Level1> <Level2>2</Level2> <Level3>3</Level3> </SubRoot> </Root> 

My code

 for subroot in root.findall('SubRoot'): level1 = subroot.find('Level1').text level2 = subroot.find('Level2').text level3 = subroot.find('Level3').text level4 = subroot.find('Level4').text print level1 print level2 print level3 print level4 

The first SubRoot contains 4 levels, the second contains 3. The string l evel4 = subroot.find('Level4').text causes an error.
How to make it so that in the column header of the csv file there are 4 levels, the first row is full, and in the last cell of the second row it is empty.
An example in the image below. enter image description here

    1 answer 1

    To get an empty string if the element does not exist:

     level4 = subroot.findtext('Level4', default='')