Python中如何读取xml的数据
生活随笔
收集整理的這篇文章主要介紹了
Python中如何读取xml的数据
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
?
<?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>?
處理的xml文件如上圖:
Python代碼:
#coding =utf-8 import xml.dom.minidom dom=xml.dom.minidom.parse('D:\Python27\lianxidanma\info.xml') root=dom.documentElementlogin=root.getElementsByTagName('login') logins=login[0] username=logins.getAttribute('username') print username password=logins.getAttribute('passwd') print passwordcaptions=root.getElementsByTagName('caption') #c1=captions[0] #print c1.firstChild.data print len(captions)for i in range(len(captions)):print captions[i].firstChild.data?
xml.dom.minidom?模塊被用來處理xml文件,所以要先引入。
xml.dom.minidom.parse()?用于打開一個(gè)xml文件,并將這個(gè)文件對(duì)象dom變量。
documentElement?用于得到dom對(duì)象的文檔元素,并把獲得的對(duì)象給root
getElementsByTagName()用于獲取標(biāo)簽
getAttribute()根據(jù)標(biāo)簽獲取標(biāo)簽中的屬性值
firstChild.data根據(jù)標(biāo)簽獲取標(biāo)簽之間的值
轉(zhuǎn)載于:https://www.cnblogs.com/HCT118/p/4504289.html
總結(jié)
以上是生活随笔為你收集整理的Python中如何读取xml的数据的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 明基DW2000如何刷新固件?
- 下一篇: python2.7虚拟环境virtual