Address: 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 NdIn 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 > Passes = 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 > Passes = 123456 </ Passwd >
< Other > <! [CDATA [ R = 5 & remember = 0 & ur = xxx ]> </ Other >
< Config > Website. ini </ Config >
< Configname > Xxx </ Configname >
</ Websites >
</ Site >
Result:
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 ' Passes = 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 ' Passes = 123456 ' ), (U ' Other ' , U ' R = 5 & remember = 0 & ur = xxx ' ), (U ' Config ' , U ' Website. ini ' ), (U ' Configname ' , U ' Xxx ' )]
End