I have an issue to extract and save in a list some variables from an XML file. Here's a part of the XML file:
''' <CoverRequirements>
<DayOfWeekCover>
<Day>Monday</Day>
<Cover>
<Shift>E</Shift>
<Preferred>2</Preferred>
</Cover>
<Cover>
<Shift>L</Shift>
<Preferred>2</Preferred>
</Cover>
</DayOfWeekCover>
<DayOfWeekCover>
<Day>Tuesday</Day>
<Cover>
<Shift>E</Shift>
<Preferred>2</Preferred>
</Cover>
<Cover>
<Shift>L</Shift>
<Preferred>2</Preferred>
</Cover>
</DayOfWeekCover>
</CoverRequirements>
'''
Here's my code:
import xml.etree.ElementTree as ET
xmlfile = 'sprint01.xml'
tree = ET.parse(xmlfile)
root = tree.getroot()
days_week_cover = []
shift_cover = []
preferred_cover = []
for cover_data in root.find('CoverRequirements'):
#level 2
days = cover_data.find('Day')
days_week_cover.append(days.text)
#level 3
cover = cover_data.find('Cover')
shift = cover.find('Shift')
shift_cover.append(shift.text)
preferred1 = cover.find('Preferred')
preferred_cover.append(preferred1.text)
print(days_week_cover) #I get: ['Monday', 'Tuesday']
print(shift_cover) # I get ['E','E'] instead of ['E','L','E','L']
print(preferred_cover) # I get ['2','2'] instead of ['2','2','2','2']
For the variables shift_cover and preferred_cover instead of getting ['E','L','E','L'] and ['2','2','2','2'] I get ['E','E'], ['2','2']. It looks like it only save in the list the first element of the level 3, XML file. I tried some variations by including a new for in function in the level 3 code in order to iterate in all elements of the level 3 but I get an error. Any help would be appreciated, thank you ! In term of time to solve the code, is this optimal ?