今天就跟大家聊聊有關(guān)怎么在python項(xiàng)目中對(duì)xml進(jìn)行解析,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

import xml.dom.minidom
#負(fù)責(zé)解析xml文件的包
from xml.dom.minidom import parse
#使用minidom打開xml文件
DOMTree = xml.dom.minidom.parse("D30_1_XmlNameSpace.xml")
print(DOMTree)#將該XML文件定義為一個(gè)對(duì)象
#得到文檔對(duì)象
doc = DOMTree.documentElement#打印出了帶有根目錄的名字的對(duì)象
print(doc)
#顯示子元素
for ele in doc.childNodes:
if ele.nodeName == "student:Name":
print("=======Node:{0}=======".format(ele.nodeName))
print(doc.childNodes)
if ele.nodeName == "Age":
print(ele.getAttribute("jio"))#獲取某一節(jié)點(diǎn)的屬性值
我們提供方法:
(1)以樹形結(jié)構(gòu)來表示xml;
(2)root.getiterator:得到相應(yīng)的可迭代的node集合
(3)root.iter
(4)find(node_name):查找指定node_name的節(jié)點(diǎn),返回一個(gè)node
(5)root.findall(node_name):返回多個(gè)node_name的節(jié)點(diǎn)
(6)node.tag:node對(duì)應(yīng)的tagename
(7)node.text:node的文本值
(8)node.attrib:是node的屬性的字典類型的內(nèi)容
mport xml.etree.ElementTree
root = xml.etree.ElementTree.parse("D30_1_XmlNameSpace.xml")
nodes = root.getiterator()
for node in nodes:
print("{0}---{1}".format(node.tag,node.text))
print("===========================================")
ele_room_name = root.find("Location")
print(type(ele_room_name))
print("{0}----{1}".format(ele_room_name.tag,ele_room_name.text))
print("===========================================")
ele_room_name2 = root.findall("{http://my_room}Name")#這里如果使用“room:Name”是解析不出來的
print(ele_room_name2)
for ele in ele_room_name2:
print("{0}----{1}".format(ele.tag,ele.text))
ele_room_name2 = root.findall("room:Name")
print(ele_room_name2)
for ele in ele_room_name2:
print("{0}----{1}".format(ele.tag,ele.text))
看完上述內(nèi)容,你們對(duì)怎么在python項(xiàng)目中對(duì)xml進(jìn)行解析有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。
網(wǎng)站欄目:怎么在python項(xiàng)目中對(duì)xml進(jìn)行解析-創(chuàng)新互聯(lián)
網(wǎng)頁地址:http://chinadenli.net/article4/eogie.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供微信小程序、網(wǎng)站設(shè)計(jì)公司、手機(jī)網(wǎng)站建設(shè)、做網(wǎng)站、網(wǎng)站導(dǎo)航、網(wǎng)頁設(shè)計(jì)公司
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容