在Python中使用XML

类别:编程语言 点击:0 评论:0 推荐:
今天我们写一个从XML配置文件读取数据库配置的例子:

#================================import begin
import win32com
import xml.dom.minidom
#================================import end

#================================class CDBConfig begin
#从xml文件读取数据库配置的类
class CDBConfig:
  def __init__(self,ConfigFilePath):#ConfigFilePath是配置文件的路径
    self.__ConfigFilePath=ConfigFilePath
    CDBConfig.DBConnects={}#CDBConfig.DBConnects是CDBConfig类的静态变量,用来存放数据库访问串
    self.ConfigXMLFile()

  def AddConnect(self,key,server="(localhost)",database="master",user="sa",password="",dbtype="SQLServer"):
    if dbtype=="SQLServer" :
      self.__sconn = "server=" + server + ";database=" + database + ";uid=" + user +";pwd=" + password;
      CDBConfig.DBConnects[key]=self.__sconn

  def ConfigXMLFile(self):
    self.__key = ""
    self.__server = ""
    self.__database = ""
    self.__user = ""
    self.__password = ""

    self.__xmlFile=open(self.__ConfigFilePath,'r')#只读打开配置文件
    self.__dom=xml.dom.minidom.parse(self.__xmlFile)#解析xml
    self.__xmlFile.close()
    self.__connect_elements=self.__dom.getElementsByTagName("DBConnection")


    for connect_element in self.__connect_elements:
        self.__key      = connect_element.getAttribute("Key")
        self.__server   = connect_element.getAttribute("Server")
        self.__database = connect_element.getAttribute("Database")
        self.__user     = connect_element.getAttribute("User")
        self.__password = connect_element.getAttribute("Password")
        self.AddConnect(self.__key,self.__server,self.__database,self.__user,self.__password,dbtype="SQLServer")      
       
#================================class CDBConfig end
if __name__=="__main__":
    myconns=CDBConfig("c:\DBConnects.config")
    for key in CDBConfig.DBConnects.keys():
        print key+'\n'#把每个数据库联接都打印出来
    

DBConnects.config文件格式如下,每个key代表一个数据库连接:
<DBConnections>
 <DBConnection Key="Test" Server="10.10.121.251" Database="Test" User="sa" Password="123"/>
 <DBConnection Key="Test2" Server="10.10.210.248" Database="Test" User="sa" Password="123"/>
 <DBConnection Key="Local1" Server="(local)" Database="NegoTBS" User="sa" Password="123"/>
 <DBConnection Key="Local2" Server="192.168.1.142" Database="Test" User="sa" Password="123"/>
 <DBConnection Key="NegoTBS" Server="(local)" Database="NegoTBS" User="sa" Password="123"/>
</DBConnections>以上主要是演示了怎样从xml读取配置,其他的处理以后再说,今天暂时到此,88

本文地址:http://com.8s8s.com/it/it23725.htm