本篇文章給大家分享的是有關Python中如何讀取XML文檔,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
對于剛剛接觸Python的初學者來說,他們在學習的過程中會逐漸的發現這一編程語言實際上一款功能強大應用簡單的計算機程序語言。我們今天將會為大家詳細介紹一下有關Python讀取XML文檔的相關應用方式。
最近做一個小功能,里邊包含Python讀取XML文檔的功能,封裝了一個讀取類,包括讀取xml中所有數據,返回list集合;根據***節點值讀取該節點及子節點的值
from xml.dom.minidom import parse,parseString class XmlConfig: def __init__(self,path): selfself.xmlData=self.GetXml(path) def GetText(self,nodelist): r="" for nxd in nd.childNodes: rr=r+nxd.nodeValue return r ##獲取xml所有數據 def GetXml(self,path): doc1=parse(path) st=doc1.firstChild websites= st.childNodes lstList=[] for sw in websites: if sw.nodeType==sw.ELEMENT_NODE : lsty=[] for nd in sw.childNodes: if nd.nodeType==nd.ELEMENT_NODE: ndndName= nd.nodeName ndndValue= nd.firstChild.data b=(ndName,ndValue) lsty.append(b) lstList.append(lsty) return lstList ##獲取單個節點及子節點值 def GetSingle(self,siteName): for item in self.xmlData: for k,v in item: if v==siteName: return item ##獲取單個節點及子節點值 def GetSingleDict(self,siteName): lst=self.GetSingle(siteName) dic1={} if len(lst)>0: for item in lst: dic1[item[0]]=item[1] return dic1
xml文檔
< ?xml version="1.0" encoding="UTF-8"?> < Site> < WebSites> < website>http://www.xxx.net< /website> < loginurl>http:///www.xxx.net/login.php< /loginurl> < username>uname=xxx< /username> < passwd>pass=123456< /passwd> < other>< ![CDATA[r=5&remember=0&ur=xxx]]>< /other> < config>WebSite.ini< /config> < configname>XXX< /configname> < /WebSites> < WebSites> < website>http://www.xxx.com< /website> < loginurl>http:///www.xxx.com/login.php< /loginurl> < username>uname=xxx< /username> < passwd>pass=123456< /passwd> < other>< ![CDATA[r=5&remember=0&ur=xxx]]>< /other> < config>WebSite.ini< /config> < configname>XXX< /configname> < /WebSites> < /Site>
Python讀取XML文檔的調用:
if __name__=="__main__": f=XmlConfig() print f.xmlData
以上就是Python中如何讀取XML文檔,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。