python 讀取xml文檔

來源:互聯網
上載者:User

原文地址:http://www.cnblogs.com/lgcf/archive/2009/09/25/1573863.html

test.py

from xml.dom.minidom import parse,parseString
class XmlConfig:
def __init__(self,path):
self.xmlData=self.GetXml(path)
def GetText(self,nodelist):
r=""
for nxd in nd.childNodes:
r=r+nxd.nodeValue
return r
def GetXml(self,path):
doc=parse(path)
st=doc.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:
ndName= nd.nodeName
ndValue= 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)
dic={}
if len(lst)>0:
for item in lst:
dic[item[0]]=item[1]
return dic

if __name__=="__main__":
f=XmlConfig("test.xml")
print f.xmlData

test.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>

結果:

m@m-desktop:~/.wkl/a$ python test.py 
[[(u'website', u'http://www.xxx.net'), (u'loginurl', u'http:///www.xxx.net/login.php'), (u'username', u'uname=xxx'), (u'passwd', u'pass=123456'), (u'other', u'r=5&remember=0&ur=xxx'), (u'config', u'WebSite.ini'), (u'configname', u'XXX')], [(u'website', u'http://www.xxx.com'), (u'loginurl', u'http:///www.xxx.com/login.php'), (u'username', u'uname=xxx'), (u'passwd', u'pass=123456'), (u'other', u'r=5&remember=0&ur=xxx'), (u'config', u'WebSite.ini'), (u'configname', u'XXX')]]

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.