本文實例講述了Python基于dom操作xml數據的方法。分享給大家供大家參考,具體如下:
1、xml的內容為del.xml,如下
<?xml version="1.0" encoding="utf-8"?><catalog> <maxid>4</maxid> <login username="pytest" passwd='123456'> <caption>Python</caption> <item id="4"> <caption>test</caption> </item> </login> <item id="2"> <caption>Zope</caption> </item></catalog>
2、python的代碼如下
# -*- coding:utf-8 -*-#! python3#1、獲得標簽屬性print("#1、獲得標簽屬性")import xml.dom.minidomdom = xml.dom.minidom.parse("del.xml") #打開xml文檔root = dom.documentElement #得到xml文檔print("nodeName:",root.nodeName) #print("nodeValue:",root.nodeValue)print("nodeType:",root.nodeType)print("ELEMENT_NODE:",root.ELEMENT_NODE)#2、獲得子標簽print("#2、獲得子標簽")bb = root.getElementsByTagName('maxid')print(type(bb))print(bb)b = bb[0]print(b.nodeName)print(b.nodeValue)#3、獲取標簽屬性值print("#3、獲取標簽屬性值")itemlist = root.getElementsByTagName('login')item =itemlist[0]print(item.getAttribute("username"))print(item.getAttribute("passwd"))itemlist = root.getElementsByTagName('item')item = itemlist[0]   #通過在itemlist中的位置區分print(item.getAttribute("id"))item_1 = itemlist[1]  #通過在itemlist中的位置區分print(item_1.getAttribute("id"))#4、獲得標簽對之間的數據print("#4、獲得標簽對之間的數據")itemlist1 = root.getElementsByTagName('caption')item1 = itemlist1[0]print(item1.firstChild.data)item2 = itemlist1[1]print(item2.firstChild.data)#5總結# minidom.parse(filename)# 加載讀取XML文件## doc.documentElement# 獲取XML文檔對象## node.getAttribute(AttributeName)# 獲取XML節點屬性值## node.getElementsByTagName(TagName)# 獲取XML節點對象集合## node.childNodes # 返回子節點列表。## node.childNodes[index].nodeValue# 獲取XML節點值## node.firstChild# # 訪問第一個節點。等價于pagexml.childNodes[0]3、運行結果如下:
#1、獲得標簽屬性
nodeName: catalog
nodeValue: None
nodeType: 1
ELEMENT_NODE: 1
#2、獲得子標簽
<class 'xml.dom.minicompat.NodeList'>
[<DOM Element: maxid at 0x1dad800>]
maxid
None
#3、獲取標簽屬性值
pytest
123456
4
2
#4、獲得標簽對之間的數據
Python
test
運行結果截圖:
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答