# 读取xml文件数据

脚本
#-*- coding:utf-8 -*-
import xml.dom.minidom
import MySQLdb
import traceback
dom = xml.dom.minidom.parse('s.xml')
root = dom.documentElement

# --------------------------------- read xml file data ----------------------------
num = root.getElementsByTagName("server")

# 定义函数获取指定标xml记名称的值, 所有值依序存入列表,返回列表
def getValue(tag=''):
name = tag
name = []
a = root.getElementsByTagName(tag)
i = 0
while i < len(a):
rc = ""
b = a[i].childNodes
c = str(b[0].data)
name.append(c)
i = i+1
return name

serverserial = getValue("serverserial")
wip = getValue("wip")
lip = getValue("lip")
os = getValue("os")
app = getValue("app")
option = getValue("option")

# 按规则组合值写成sql,写入数据库
v = ''
for i in range(len(num)):
# print serverserial[i],wip[i],lip[i],os[i],app[i],option[i]
v = v+"('%s','%s','%s','%s','%s',CURRENT_TIMESTAMP(),'%s')," % (serverserial[i],wip[i],lip[i],os[i],app[i],option[i])

sql = str('insert into ty_server_list(servername,server,server_lip,server_op,server_app,updatetime,server_type) values'+v.rstrip(','))

db = MySQLdb.connect(host='localhost',passwd='wwtest',user='root',db='test',port=3306)
try:
a = db.cursor() # 执行插入值的SQL
a.execute(sql)
except:
print "\nSource SQL ERROR ! "
print "--------------------------------\n"+traceback.format_exc()+"--------------------------------\n"

cursor = db.cursor() ##查询执行后数据库现有数据
cursor.execute("select servername,server,server_lip,server_op,server_app,updatetime,server_type from ty_server_list")
result = cursor.fetchall()

print "Query Table Result:\n-----------------------------------------------------------------------------"
for record in result:
print record

db.close()
print "\n"
# --------------------------------- read xml file data ----------------------------

最后更新: 2018年10月22日 16:44

原始链接: http://cwiwi.com/2018/10/22/duquxmlwenjianshuju/