Python中如何读取xml的数据
生活随笔
收集整理的這篇文章主要介紹了
Python中如何读取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>?
處理的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()?用于打開一個xml文件,并將這個文件對象dom變量。
documentElement?用于得到dom對象的文檔元素,并把獲得的對象給root
getElementsByTagName()用于獲取標簽
getAttribute()根據標簽獲取標簽中的屬性值
firstChild.data根據標簽獲取標簽之間的值
轉載于:https://www.cnblogs.com/HCT118/p/4504289.html
總結
以上是生活随笔為你收集整理的Python中如何读取xml的数据的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 明基DW2000如何刷新固件?
- 下一篇: python2.7虚拟环境virtual