创建一个xml文件Class_info.xml 用来存储班级学生(姓名,年龄,城市),老师(姓名,年龄,城市)、教务账号(学生和老师的账号,密码)等信息。
<?xml version="1.0" encoding="UTF-8" ?> <Class> <student> <name >Jack</name> <age>28</age> <city>Beijing</city> </student> <student> <name >Bob</name> <age>25</age> <city>Shanghai</city> </student> <student> <name>Harry</name> <age>23</age> <city>ShenZhen</city> </student> <teacher> <name>Marry</name> <age>23</age> <city>Changsha</city> </teacher> <account> <login username="student" password="123456"/> <login username="teacher" password="888888"/> </account> </Class>
from xml.dom import minidom
dom = minidom.parse("Class_info.xml")
root = dom.documentElement #加载全部元素
#根据标签名称获取标签对象
names=root.getElementsByTagName('name')
ages=root.getElementsByTagName('age')
citys=root.getElementsByTagName('city')
#分别打印显示xml文档标签对里面的内容
print(names[0].firstChild.data)
print(ages[0].firstChild.data)
print(citys[0].firstChild.data)
可以for 循环全部取参
--------------------------------------------------------------------------
login = root.getElementsByTagName("login")
# print(login)
username = login[0].getAttribute("username")
password = login[0].getAttribute("password")
print(username)
print(password)
-------------------------------------------------------------------------------------
tags=root.getElementsByTagName('student')
print(tags[0].nodeName)
print(tags[0].tagName)
print(tags[0].nodeType)
print(tags[0].nodeValue)