The use of xml

<?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>

 

Read element node

Import the minidom xml.dom from 


dom = minidom.parse ( "./ info.xml") # load xml files
root = dom.documentElement # load the object element dom

Print (root.nodeName)
Print (root.nodeValue)
Print (root. nodeType)

 

To read the property value of the node

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)

 

 

 

Reads the specified node's children
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)

 

 探索-读取指定节点下面的节点值

from xml.dom import minidom

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

tags=root.getElementsByTagName("banji")

print(tags[0].firstChild.data)

 

 



Guess you like

Origin www.cnblogs.com/wyx1990/p/12006410.html