import xml.etree.ElementTree as ET
mytree = ET.parse('members.xml') # to parse file
print(mytree.tag) # to get root tag
children = list(mytree) # to get children element
Вот простой для l oop вывод содержимого, построения 2D-массива и списка словарей (это я предпочитаю):
import xml.etree.ElementTree as ET
mytree = ET.parse('members.xml') # to parse file
print(mytree.tag) # to get root tag
children = list(mytree) # to get children element
arr = [] # 2D array
dic = [] # list of dict
for e in list(mytree):
print(e.tag) # prints "member"
ch = list(e) # get its children
element = []
elementdict = {}
for ee in ch:
print("\t", ee.tag, ":", ee.text)
element.append(ee.text) # add text to arr[i]
elementdict[ee.tag] = ee.text # add text to dictionnary
arr.append(element)
dic.append(elementdict)
print(arr) ## print 2D array
print(dic) ## print list of dictionaries
Вывод:
member
FirstName : Jarrod
LastName : Weiss
DOB : 12-08-1991
DateJoined : 4-05-2017
Paid : TRUE
member
FirstName : John
LastName : Smith
DOB : 22-09-1980
DateJoined : 1-03-2016
Paid : TRUE
## print(arr)
[['Jarrod', 'Weiss', '12-08-1991', '4-05-2017', 'TRUE'], ['John', 'Smith', '22-09-1980', '1-03-2016', 'TRUE']]
## print(dic)
[{'FirstName': 'Jarrod', 'LastName': 'Weiss', 'DOB': '12-08-1991', 'DateJoined': '4-05-2017', 'Paid': 'TRUE'}, {'FirstName': 'John', 'LastName': 'Smith', 'DOB': '22-09-1980', 'DateJoined': '1-03-2016', 'Paid': 'TRUE'}]