博客园开博第一篇,奉上最近做的python读取xml文档的例子
最近做一个小功能,里边包含python读取xml配置文件的功能,封装了一个读取类,包括读取xml中所有数据,返回list集合;根据唯一节点值读取该节点及子节点的值
Code
1 from xml.dom.minidom import parse,parseString
2 class XmlConfig:
3 def __init__(self,path):
4 self.xmlData=self.GetXml(path)
5 def GetText(self,nodelist):
6 r=""
7 for nxd in nd.childNodes:
8 r=r+nxd.nodeValue
9 return r
10
11 ##获取xml所有数据
12 def GetXml(self,path):
13 doc1=parse(path)
14 st=doc1.firstChild
15 websites= st.childNodes
16
17 lstList=[]
18 for sw in websites:
19 if sw.nodeType==sw.ELEMENT_NODE :
20 lsty=[]
21 for nd in sw.childNodes:
22 if nd.nodeType==nd.ELEMENT_NODE:
23 ndName= nd.nodeName
24 ndValue= nd.firstChild.data
25 b=(ndName,ndValue)
26 lsty.append(b)
27 lstList.append(lsty)
28 return lstList
29
30 ##获取单个节点及子节点值
31 def GetSingle(self,siteName):
32 for item in self.xmlData:
33 for k,v in item:
34 if v==siteName:
35 return item
36
37 ##获取单个节点及子节点值
38 def GetSingleDict(self,siteName):
39 lst=self.GetSingle(siteName)
40 dic1={}
41 if len(lst)>0:
42 for item in lst:
43 dic1[item[0]]=item[1]
44 return dic1
xml文档
Code
<?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>
调用
if __name__=="__main__":
f=XmlConfig()
print f.xmlData