本文實例講述了Python使用MYSQLDB實現從數據庫中導出XML文件的方法。分享給大家供大家參考。具體分析如下:
這里需要給前端以xml格式提供一些數據,這些數據在目前的數據庫中已經存在。
如果使用django返回xml數據的話,需要包裝下頭信息:
簡單的舉個例子:
# -*- coding: utf-8 -*-from xml.dom import minidomimport MySQLdbconn = MySQLdb.connect(host='localhost',user='root',passwd='xxx',db='my_xml',charset="utf8")cursor = conn.cursor()cursor.execute('select id, name, style, description, family from ppy_fish')res_list = cursor.fetchall()print len(res_list)doc = minidom.Document()root = doc.createElement("data")doc.appendChild(root)ATTRIBUTE = {"n":1, "d":3}for res in res_list: node = doc.createElement(res[2]) for i in ATTRIBUTE: id_node = doc.createElement("%s" % i) data = doc.createTextNode("%s" % res[ATTRIBUTE[i]]) id_node.appendChild(data) node.appendChild(id_node) root.appendChild(node)str_xml = doc.toxml("utf-8")f = open('fish.xml', 'w')f.write(str_xml)f.close()cursor.close()conn.close()希望本文所述對大家的Python程序設計有所幫助。
新聞熱點
疑難解答
圖片精選