国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Python > 正文

Python基于dom操作xml數(shù)據(jù)的方法示例

2020-02-23 00:06:02
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

本文實(shí)例講述了Python基于dom操作xml數(shù)據(jù)的方法。分享給大家供大家參考,具體如下:

1、xml的內(nèi)容為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、獲得標(biāo)簽屬性print("#1、獲得標(biāo)簽屬性")import xml.dom.minidomdom = xml.dom.minidom.parse("del.xml") #打開(kāi)xml文檔root = dom.documentElement #得到xml文檔print("nodeName:",root.nodeName) #print("nodeValue:",root.nodeValue)print("nodeType:",root.nodeType)print("ELEMENT_NODE:",root.ELEMENT_NODE)#2、獲得子標(biāo)簽print("#2、獲得子標(biāo)簽")bb = root.getElementsByTagName('maxid')print(type(bb))print(bb)b = bb[0]print(b.nodeName)print(b.nodeValue)#3、獲取標(biāo)簽屬性值print("#3、獲取標(biāo)簽屬性值")itemlist = root.getElementsByTagName('login')item =itemlist[0]print(item.getAttribute("username"))print(item.getAttribute("passwd"))itemlist = root.getElementsByTagName('item')item = itemlist[0]   #通過(guò)在itemlist中的位置區(qū)分print(item.getAttribute("id"))item_1 = itemlist[1]  #通過(guò)在itemlist中的位置區(qū)分print(item_1.getAttribute("id"))#4、獲得標(biāo)簽對(duì)之間的數(shù)據(jù)print("#4、獲得標(biāo)簽對(duì)之間的數(shù)據(jù)")itemlist1 = root.getElementsByTagName('caption')item1 = itemlist1[0]print(item1.firstChild.data)item2 = itemlist1[1]print(item2.firstChild.data)#5總結(jié)# minidom.parse(filename)# 加載讀取XML文件## doc.documentElement# 獲取XML文檔對(duì)象## node.getAttribute(AttributeName)# 獲取XML節(jié)點(diǎn)屬性值## node.getElementsByTagName(TagName)# 獲取XML節(jié)點(diǎn)對(duì)象集合## node.childNodes # 返回子節(jié)點(diǎn)列表。## node.childNodes[index].nodeValue# 獲取XML節(jié)點(diǎn)值## node.firstChild# # 訪問(wèn)第一個(gè)節(jié)點(diǎn)。等價(jià)于pagexml.childNodes[0]

3、運(yùn)行結(jié)果如下:

#1、獲得標(biāo)簽屬性
nodeName: catalog
nodeValue: None
nodeType: 1
ELEMENT_NODE: 1
#2、獲得子標(biāo)簽
<class 'xml.dom.minicompat.NodeList'>
[<DOM Element: maxid at 0x1dad800>]
maxid
None
#3、獲取標(biāo)簽屬性值
pytest
123456
4
2
#4、獲得標(biāo)簽對(duì)之間的數(shù)據(jù)
Python
test

運(yùn)行結(jié)果截圖:

PS:這里再為大家提供幾款關(guān)于xml操作的在線工具供大家參考使用:

在線XML/JSON互相轉(zhuǎn)換工具:
http://tools.jb51.net/code/xmljson

在線格式化XML/在線壓縮XML:
http://tools.jb51.net/code/xmlformat

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 五指山市| 洞头县| 柳河县| 资溪县| 神农架林区| 江川县| 比如县| 从化市| 岚皋县| 民县| 忻州市| 峨眉山市| 会理县| 赞皇县| 永丰县| 南城县| 福鼎市| 团风县| 元谋县| 田阳县| 南川市| 四子王旗| 太谷县| 会宁县| 洛阳市| 乳山市| 绩溪县| 陆良县| 仙桃市| 库尔勒市| 神农架林区| 平利县| 东乌珠穆沁旗| 沿河| 紫云| 乐业县| 瑞丽市| 封开县| 香河县| 海阳市| 曲麻莱县|