# python读取db数据生成xml文件,美化格式输出

脚本
#-*- coding:utf-8 -*-
#date: 2013/05/30

import xml.dom.minidom
import sys,codecs
import MySQLdb
impl=xml.dom.minidom.getDOMImplementation()
dom=impl.createDocument(None,'wml',None)
root=dom.documentElement

def Indent(dom, node, indent = 0):
# Copy child list because it will change soon
children = node.childNodes[:]
# Main node doesn't need to be indented
if indent:
text = dom.createTextNode('\n' + '\t' * indent)
node.parentNode.insertBefore(text, node)
if children:
# Append newline after last child, except for text nodes
if children[-1].nodeType == node.ELEMENT_NODE:
text = dom.createTextNode('\n' + '\t' * indent)
node.appendChild(text)
# Indent children which are elements
for n in children:
if n.nodeType == node.ELEMENT_NODE:
Indent(dom, n, indent + 1)

def getNode(s1='',s2='',s3='',s4='',s5='',s6='',s7=''):

serverserial=dom.createElement('serverserial')
serverserialvalue=dom.createTextNode('%s'% s1)
serverserial.appendChild(serverserialvalue)

wip=dom.createElement('wip')
wipvalue=dom.createTextNode('%s'% s2)
wip.appendChild(wipvalue)

lip=dom.createElement('lip')
lipvalue=dom.createTextNode('%s'% s3)
lip.appendChild(lipvalue)

os=dom.createElement('os')
osvalue=dom.createTextNode('%s'% s4)
os.appendChild(osvalue)

app=dom.createElement('app')
appvalue=dom.createTextNode('%s'% s5)
app.appendChild(appvalue)

locate=dom.createElement('locate')
locatevalue=dom.createTextNode('%s'% s6)
locate.appendChild(locatevalue)

option=dom.createElement('option')
optionvalue=dom.createTextNode('%s'% s7)
option.appendChild(optionvalue)

server=dom.createElement('server')
server.setAttribute('ip','%s'% s2)

server.appendChild(serverserial)
server.appendChild(wip)
server.appendChild(lip)
server.appendChild(os)
server.appendChild(app)
server.appendChild(locate)
server.appendChild(option)

root.appendChild(server)


db=MySQLdb.connect(host='localhost',user='root',passwd='wwtest',db='test')
cursor=db.cursor()
cursor.execute('select servername,server,server_lip,server_op,server_app,updatetime,server_type from ty_server_list')
result=cursor.fetchall()
for record in result:
print record
getNode(record[0],record[1],record[2],record[3],record[4],record[5],record[6])

db.close()

domcopy=dom.cloneNode(True)
Indent(domcopy,domcopy.documentElement)

f=file(sys.path[0]+'/backup/wwtest.xml','w')
write=codecs.lookup('utf-8')[3](f)
#dom.writexml(write,encoding='utf-8')
domcopy.writexml(write,encoding='utf-8')
domcopy.unlink()
f.close()

最后更新: 2018年10月22日 17:14

原始链接: http://cwiwi.com/2018/10/22/python-read-dbdata-to-xml/