<?xml version="1.0" encoding="UTF-8"?> <Class> <student> <name>zhangsan</name> <age>23</age> <city>beijing</city> </student> <student> <name>lisi</name> <age>21</age> <city>shanghai</city> </student> <student> <name>wangwu</name> <age>22</age> <city>shenzhen</city> </student> <teacher> <name>marry</name> <age>53</age> <city>changsha</city> </teacher> <account> <login username="student" password="123456"/> <login username="teacher" password="654321"/> </account> </Class>
from xml.dom import minidom dom=minidom.parse('C:\Users\Administrator\Desktop\python-test\test7.xml') root=dom.documentElement #打印节点信息 print(root.nodeName) #节点名称 print(root.nodeValue) #节点值 print(root.nodeType) #节点类型,如果是元素节点返回1,属性节点返回2 print('=============================') #读取文本节点的值 names=root.getElementsByTagName('name') ages=root.getElementsByTagName('age') citys=root.getElementsByTagName('city') print(names[0].firstChild.data) print(ages[0].firstChild.data) print(citys[0].firstChild.data) print('=============================') #获取属性节点的值 logins=root.getElementsByTagName('login') username=logins[0].getAttribute('username') print(username) password=logins[0].getAttribute('password') print(password) print('=============================') #打印xml子节点 tags=root.getElementsByTagName('student') print(tags[0].nodeName) #节点名称 print(tags[0].nodeValue) #节点值 print(tags[0].nodeType) #节点类型