读取xml文件的方法
1.xml文件【例子】
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <page> <database name="CREDIT"> <table name="customter"> <sql id="001"> select t.*,rowid from customter t where cust_code=(select fk_cust_code from lb_t_into_info where into_app_id='130154740318') </sql> </table> <table name="T_TN_TRANSACTION_RECORD"> <sql id="002"> select * from RECORD a where bus_code = '%s' order by a.create_time desc </sql> </table> </database> <database name="CORE"> <table name="loan"> <sql id="003"> select * from loan t where t.loan_status = '0' and t.contract_no in (select t1.contract_no from paymentw t1 where t1.pay_status not in ('0','1','2,','3')) order by id desc </sql> </table> </database> </page>
2.获取xml里的sql数据
# -*- coding: utf-8 -*- from xml.etree import ElementTree class OperationXml: # 构造函数,就是实例化就会出现的东西 def __init__(self,sql_path): self.sql_path = sql_path self.database = {} #从SQL.xml中读取SQL数据 def set_xml(self): if len(self.database) == 0: tree = ElementTree.parse(sql_path) for db in tree.findall("database"): #tree.findall("*")获取整个结构树 db_name = db.get("name") table = {} for tb in db.getchildren(): #db.getchildren()获取子节点 table_name = tb.get("name") #print(table_name) sql = {} for data in tb.getchildren(): sql_id = data.get("id") #print(sql_id) sql[sql_id] = data.text.strip() table[table_name] = sql self.database[db_name] = table def get_xml_dict(self,database_name, table_name): self.set_xml() database_dict = self.database.get(database_name).get(table_name) return database_dict # 读取的SQL.xml文件 def get_sql(self,database_name, table_name, sql_id): db = self.get_xml_dict(database_name, table_name) sql = db.get(sql_id) return sql if __name__ == '__main__': from Util.var import sql_path
path = os.path.dirname(os.path.abspath(__file__))
config_path = os.path.join(path, 'SQL.xml')
tree = ElementTree.parse(config_path)
oper = OperationXml(sql_path) SQL1 = oper.get_sql("CORE","loan","003") print(SQL1)
一切技术都是为业务服务,脱离业务的技术一文不值!