import xml.etree.ElementTree as ET
STUDENTS = [('ST1','Jhone'),('ST5','Pitter'),('ST77','Arik')]
def indent(elem, level=0):
i = "\n" + level*" "
j = "\n" + (level-1)*" "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for subelem in elem:
indent(subelem, level+1)
if not elem.tail or not elem.tail.strip():
elem.tail = j
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = j
return elem
def find_student_by_id(doc,_id):
arg = ".//student[@id='{}']".format(_id)
return doc.findall(arg)
# build the XML document
root = ET.Element('students')
for student in STUDENTS:
student_element = ET.SubElement(root, 'student')
student_element.set('name',student[1])
student_element.set('id',student[0])
# print the xml document
indent(root)
ET.dump(root)
# search the document by id
student = find_student_by_id(root,'ST1')
# found
print(student)
student = find_student_by_id(root,'ST111')
# not found
print(student)