python 读取xml文档

原文地址: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')]]







原文地址:https://www.cnblogs.com/wangkangluo1/p/2186460.html