Python讀取XML文檔正確應用方式解讀
作者:佚名
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文檔的相關介紹。
【編輯推薦】
責任編輯:曹凱
來源:
博客園