from xml.dom.minidom import parse dom1 = parse("Test.xml") students = dom1.getElementsByTagName("student") for student in students: id = student.getAttribute("id") name = student.getElementsByTagName("name")[0] sex = student.getElementsByTagName("sex")[0] print('ID : %s, Name : %s, Sex : %s' % (id, name.childNodes[0].nodeValue, sex.childNodes[0].nodeValue)) subjects = student.getElementsByTagName("subjects") for sub in subjects: math = sub.getElementsByTagName("math")[0] english = sub.getElementsByTagName("english")[0] print("Math : %s, English : %s" % (math.childNodes[0].nodeValue, english.childNodes[0].nodeValue))
输出结果:
ID : 001, Name : Du Liu, Sex : Male
Math : 90, English : 85
ID : 002, Name : Lao Zhang, Sex : Female
Math : 100, English : 60