利用python实现xml与数据库读取转换的方法


Posted in Python onJune 17, 2017

前言

xml课的第三第四个作业都是用java编程来实现xml dom的一些转换, 因为自己没怎么学过java,因此和老师说了下想用python来实现第三第四个作业,下面就直接贴代码了

xml文档

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="1.xslt" rel="external nofollow" ?>
<!DOCTYPE sys_info [
 <!ELEMENT sys_info (info+)>
 <!ELEMENT info (sysDescr,sysUpTime,sysContact,sysName)>
 <!ELEMENT sysDescr (#PCDATA)>
 <!ELEMENT sysUpTime (#PCDATA)>
 <!ELEMENT sysContact (#PCDATA)>
 <!ELEMENT sysName (#PCDATA)>
 <!ATTLIST info ip CDATA #REQUIRED>
]>
 
<sys_info xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="1.xsd">
 <info ip="192.168.1.1">
  <sysDescr>X86-Windows2000</sysDescr>
  <sysUpTime>9 hours 42 minutes</sysUpTime>
  <sysContact>zhangsan</sysContact>
  <sysName>computerZhang</sysName>
 
 </info>
 <info ip="192.168.1.3">
  <sysDescr>router</sysDescr>
  <sysUpTime>24 hours</sysUpTime>
  <sysContact>ruijie</sysContact>
  <sysName>Router2</sysName>
 </info>
 <info ip="192.168.2.1">
  <sysDescr>router</sysDescr>
  <sysUpTime>89 hours</sysUpTime>
  <sysContact>Cisco</sysContact>
  <sysName>Router3</sysName>
 </info>
</sys_info>

解析xml文档用的是python自带的xml库ElementTree, 读取mysql可以安装MySQLdb模块

apt-get install python-MySQLdb

程序运行如下

root@lj /h/s/x/3# python 21.py -h
usage: 21.py [-h] status
 
positional arguments:
 status  0clar,1read,2insert

读取xml保存到数据库

root@lj /h/s/x/3# python 21.py 2
插入语句: insert into info values ('192.168.1.1','X86-Windows2000','9 hours 42 minutes','zhangsan','computerZhang')
插入语句: insert into info values ('192.168.1.3','router','24 hours','ruijie','Router2')
插入语句: insert into info values ('192.168.2.1','router','89 hours','Cisco','Router3')
insert success!!!

读取数据库保存到xml文档

root@lj /h/s/x/3# python 21.py 1
+-------------+-----------------+--------------------+------------+---------------+
| IP地址 | sysDescr.0 | sysUpTime.0  | sysContact | sysName.0 |
+-------------+-----------------+--------------------+------------+---------------+
| 192.168.1.1 | X86-Windows2000 | 9 hours 42 minutes | zhangsan | computerZhang |
| 192.168.1.3 |  router  |  24 hours  | ruijie | Router2 |
| 192.168.2.1 |  router  |  89 hours  | Cisco | Router3 |
+-------------+-----------------+--------------------+------------+---------------+
write into sys.xml...

建立数据库的sql文件:

-- MySQL dump 10.16 Distrib 10.1.21-MariaDB, for debian-linux-gnu (x86_64)
--
-- Host: localhost Database: localhost
-- ------------------------------------------------------
-- Server version 10.1.21-MariaDB-5
 
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
 
--
-- Table structure for table `info`
--
 
DROP TABLE IF EXISTS `info`;
/*!40101 SET @saved_cs_client  = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `info` (
 `ip` char(15) NOT NULL,
 `sysDescr` varchar(20) DEFAULT NULL,
 `sysUpTime` varchar(40) DEFAULT NULL,
 `sysContract` varchar(20) DEFAULT NULL,
 `sysName` varchar(20) DEFAULT NULL,
 PRIMARY KEY (`ip`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
 
--
-- Dumping data for table `info`
--
 
LOCK TABLES `info` WRITE;
/*!40000 ALTER TABLE `info` DISABLE KEYS */;
INSERT INTO `info` VALUES ('192.168.1.1','X86-Windows2000','9 hours 42 minutes','zhangsan','computerZhang'),('192.168.1.3','router','24 hours','ruijie','Router2'),('192.168.2.1','router','89 hours','Cisco','Router3');
/*!40000 ALTER TABLE `info` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
 
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
 
-- Dump completed on 2017-03-23 15:36:31

下面是主要代码

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-03-23 14:47:39
# @Author : 江sir (2461805286@qq.com)
# @Link : http://www.blogsir.com.cn
# @Version : $1.1
 
import sys
import xml.etree.ElementTree as ET
import MySQLdb
import argparse
from prettytable import PrettyTable 
 
'''
一个xml作业,自己用python实现了从xml读取到数据库,和从数据库读取到xml的功能
'''
 
def buildNewsXmlFile(data):
 
 
 root = ET.Element('sys_info')#创建sys_info根元素
 # print help(ET)
 info = ET.SubElement(root, "info",attrib={'ip':'%s'%data[0][0]})#创建四个二级元素
 sysDescr = ET.SubElement(info,"sysDescr")
 sysUpTime = ET.SubElement(info,"sysUpTime")
 sysContact = ET.SubElement(info,"sysContact")
 sysName = ET.SubElement(info,"sysName")
 sysDescr.text = data[0][1]
 sysUpTime.text = data[0][2]
 sysContact.text = data[0][3]
 sysName.text = data[0][4]
 
 info = ET.SubElement(root, "info",attrib={'ip':'%s'%data[1][0]})
 sysDescr = ET.SubElement(info,"sysDescr")
 sysUpTime = ET.SubElement(info,"sysUpTime")
 sysContact = ET.SubElement(info,"sysContact")
 sysName = ET.SubElement(info,"sysName")
 sysDescr.text = data[1][1]
 sysUpTime.text = data[1][2]
 sysContact.text = data[1][3]
 sysName.text = data[1][4]
 
 info = ET.SubElement(root, "info",attrib={'ip':'%s'%data[2][0]})
 sysDescr = ET.SubElement(info,"sysDescr")
 sysUpTime = ET.SubElement(info,"sysUpTime")
 sysContact = ET.SubElement(info,"sysContact")
 sysName = ET.SubElement(info,"sysName")
 sysDescr.text = data[2][1]
 sysUpTime.text = data[2][2]
 sysContact.text = data[2][3]
 sysName.text = data[2][4]
 
 print 'write into sys.xml...'
 tree = ET.ElementTree(root)
 tree.write("sys.xml")
 
 
def xml_parser():
 data = {}
 data_list = []
 tree = ET.parse('21.xml')
 root = tree.getroot()# 获取根元素
 for info in root.findall('info'): #查找所有info元素
  for child in info: #对每个info元素遍历属性和子节点
   data ['ip']= info.attrib['ip']
   data[child.tag] = child.text
 
  # print data.values()
  data_list.append(data.values())
 
 
 # print data_list
 return data_list
 
 
 
def get_Mysql():
 conn = MySQLdb.connect('localhost','root','root','sys_info2',charset='utf8')
 cursor = conn.cursor()
 cursor.execute('select * from info');
 result = cursor.fetchall()
 if not result:
  print 'please insert the database first'
  sys.exit()
 
 
 x = PrettyTable(['IP地址','sysDescr.0','sysUpTime.0','sysContact','sysName.0'])
 for i in result:
  x.add_row(i)
 print x
 
 # print result
 return result
 
def set_Mysql(data):
 conn = MySQLdb.connect('localhost','root','root','sys_info2',charset='utf8')
 cursor = conn.cursor()
 for i in data:
  # print tuple(i)
  sysName,ip,sysUpTime,sysDescr,sysContact = tuple(i)
  sql = "insert into info values ('%s','%s','%s','%s','%s')"%(ip,sysDescr,sysUpTime,sysContact,sysName)
  print '插入语句:',sql
  try:
   cursor.execute(sql)
  except:
   print 'please clear the database'
   sys.exit()
 print 'insert success!!!'
 conn.commit()
 conn.close()
 
 
def clear_Mysql():
 conn = MySQLdb.connect('localhost','root','root','sys_info2',charset='utf8')
 cursor = conn.cursor()
 cursor.execute('delete from info')
 conn.commit()
 conn.close()
 
 
def main():
 parser = argparse.ArgumentParser()
 parser.add_argument('status',type=int,help="0clar,1read,2insert")
 arg = parser.parse_args()
 # print arg
 status = arg.status
 if status == 1:
  data = get_Mysql()
  buildNewsXmlFile(data)
 elif status == 2:
  data = xml_parser()
  set_Mysql(data)
 elif status == 0:
  clear_Mysql()
 else:
  print 'usage %s [0|1|2]'%sys.argv[0]
 
if __name__ == '__main__':
 main()

第四个作业是web编程,用python的flask框架即可快速实现一个xml文档的显示,文件过多,就不贴了

总结

以上就是这文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如有疑问大家可以留言交流,谢谢大家对三水点靠木的支持。

Python 相关文章推荐
Python中Django框架利用url来控制登录的方法
Jul 25 Python
利用Python抓取行政区划码的方法
Nov 28 Python
Django使用Celery异步任务队列的使用
Mar 13 Python
对python:print打印时加u的含义详解
Dec 15 Python
python下载微信公众号相关文章
Feb 26 Python
Pythony运维入门之Socket网络编程详解
Apr 15 Python
Python使用pyserial进行串口通信的实例
Jul 02 Python
Django model update的多种用法介绍
Mar 28 Python
Python列表删除元素del、pop()和remove()的区别小结
Sep 11 Python
Python字典的概念及常见应用实例详解
Oct 30 Python
Python+appium框架原生代码实现App自动化测试详解
Mar 06 Python
Python insert() / append() 用法 Leetcode实战演示
Mar 31 Python
用python写个自动SSH登录远程服务器的小工具(实例)
Jun 17 #Python
python中Pycharm 输出中文或打印中文乱码现象的解决办法
Jun 16 #Python
Python生成随机密码的方法
Jun 16 #Python
Python操作SQLite数据库的方法详解
Jun 16 #Python
使用python实现个性化词云的方法
Jun 16 #Python
linux环境下python中MySQLdb模块的安装方法
Jun 16 #Python
Django中利用filter与simple_tag为前端自定义函数的实现方法
Jun 15 #Python
You might like
ThinkPHP使用心得分享-上传类UploadFile的使用
2014/05/15 PHP
完美解决phpexcel导出到xls文件出现乱码的问题
2016/10/29 PHP
json-lib出现There is a cycle in the hierarchy解决办法
2010/02/24 Javascript
js的逻辑运算符 ||
2010/05/31 Javascript
js自定义方法通过隐藏iframe实现文件下载
2013/02/21 Javascript
js 距离某一时间点时间是多少实现代码
2013/10/14 Javascript
JS滚轮事件onmousewheel使用介绍
2013/11/01 Javascript
javascript中的throttle和debounce浅析
2014/06/06 Javascript
图片放大镜jquery.jqzoom.js使用实例附放大镜图标
2014/06/19 Javascript
jQuery+css3实现Ajax点击后动态删除功能的方法
2015/08/10 Javascript
Angular实现form自动布局
2016/01/28 Javascript
Angularjs中如何使用filterFilter函数过滤
2016/02/06 Javascript
浅谈js中的引用和复制(传值和传址)
2016/09/18 Javascript
Bootstrap里的文件分别代表什么意思及其引用方法
2017/05/01 Javascript
详解vue2.0 使用动态组件实现 Tab 标签页切换效果(vue-cli)
2017/08/30 Javascript
JS实现点击下拉菜单把选择的内容同步到input输入框内的实例
2018/01/23 Javascript
详解Angular5 路由传参的3种方法
2018/04/28 Javascript
详解在vue-cli3.0中自定css、js和图片的打包路径
2019/08/26 Javascript
jQuery模仿ToDoList实现简单的待办事项列表
2019/12/30 jQuery
JS highcharts动态柱状图原理及实现
2020/10/16 Javascript
Python中decorator使用实例
2015/04/14 Python
在Django的上下文中设置变量的方法
2015/07/20 Python
python traceback捕获并打印异常的方法
2018/08/31 Python
用Python和WordCloud绘制词云的实现方法(内附让字体清晰的秘笈)
2019/01/08 Python
python实现nao机器人身体躯干和腿部动作操作
2019/04/29 Python
分享8个非常流行的 Python 可视化工具包
2019/06/05 Python
Python Request爬取seo.chinaz.com百度权重网站的查询结果过程解析
2019/08/13 Python
python numpy生成等差数列、等比数列的实例
2020/02/25 Python
Python ATM功能实现代码实例
2020/03/19 Python
Python pysnmp使用方法及代码实例
2020/08/24 Python
详解Pymongo常用查询方法总结
2021/01/29 Python
美国女性奢华品牌精品店:INTERMIX
2017/10/12 全球购物
AutoShack.com加拿大:北美主要的汽车零部件零售商
2019/07/24 全球购物
Linux管理员面试经常问道的相关命令
2013/04/29 面试题
电脑饰品店的创业计划书
2014/01/21 职场文书
幼儿园教师演讲稿
2014/05/06 职场文书