<?xml version="1.0" encoding="utf-8"?>
<class>
<student>
<name>张三</name>
<age>23</age>
<city>深圳</city>
</student>
<student>
<name>李四</name>
<age>25</age>
<city>上海</city>
</student>
<teacher>
<name>老师</name>
<age>45</age>
<city>深圳</city>
</teacher>
<nianji>
<banji>二班</banji>
<other>Android</other>
</nianji>
<account>
<login username="student" password="123456" />
<login username="student" password="222222" />
</account>
</class>

读取元素节点

from xml.dom import minidom


dom=minidom.parse("./info.xml")#加载xml文件
root=dom.documentElement #加载dom对象元素

print(root.nodeName)
print(root.nodeValue)
print(root.nodeType)

读取属性节点的值

from xml.dom import minidom

dom=minidom.parse("info.xml")
root=dom.documentElement
logins=root.getElementsByTagName("login")#指定节点

for i in range(2):
username=logins[i].getAttribute("username")
print(username)
passord=logins[i].getAttribute("password")
print(passord)

 

 

读取指定节点的子节点
from xml.dom import minidom

dom=minidom.parse("info.xml")

root=dom.documentElement

tags=root.getElementsByTagName("student")

print(tags[0].nodeName)
print(tags[0].tagName)
print(tags[0].nodeType)
print(tags[0].nodeValue)

 

读取文本节点的值
from xml.dom import minidom

dom=minidom.parse("./info.xml")
root=dom.documentElement

names=root.getElementsByTagName("name")
print(names[0].firstChild.data)#读取第一个names的值

ages=root.getElementsByTagName("age")
citys=root.getElementsByTagName("city")
for i in range(3):#遍历打印names的值
print(names[i].firstChild.data)

 



12-23 05:41