Python is used to implement the conversion between xml and database reading.

Source: Internet
Author: User

Python is used to implement the conversion between xml and database reading.

Preface

In the third and fourth tasks of the xml course, java programming is used to convert the xml dom, because I have never learned java, so I told the teacher that I want to use python to implement the third and fourth jobs. I will paste the code below.

Xml document

<?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>

Parse the xml document using the ElementTree library that comes with python. Read mysql and install the MySQLdb module.

apt-get install python-MySQLdb

The program runs as follows:

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

Read xml and save it to the database

Root @ lj/h/s/x/3 # python 21.py 2 insert statement: insert into info values ('2017. 168.1.1 ', 'x86-windows2000', '9 hours 42 minutes', 'zhangsan', 'computerzhang') insert statement: insert into info values ('2017. 168.1.3 ', 'router', '24 hours', 'rouie Ie', 'router2') insert statement: insert into info values ('192. 168.2.1 ', 'router', '89 hours', 'cisco', 'router3') insert success !!!

Read the database and save it to the xml document.

Root @ lj/h/s/x/3 # python 21.py 1 + --------------- + accept + ------------ + --------------- + | IP address | sysDescr.0 | sysUpTime.0 | sysContact | sysName.0 | + -------- california + ------------ + --------------- + | 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...

Create an SQL file for the database:

-- 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

The following is the main code:

#! /Usr/bin/env python #-*-coding: UTF-8-*-# @ Date: 14:47:39 # @ Author: Jiang sir (2461805286@qq.com) # @ Link: http://www.blogsir.com.cn # @ Version: $1.1 import sysimport xml. etree. elementTree as ETimport MySQLdbimport argparsefrom prettytable import PrettyTable ''' an xml job that reads data from xml to the database using python, and '''def buildNewsXmlFile (data): root = ET. element ('sys _ info') # create sys_info root Element # print Help (ET) info = ET. subElement (root, "info", attrib = {'IP': '% s' % data [0] [0]}) # create four level-2 elements 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", Ttrib = {'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. subElemen T (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 ('2 1. xml ') root = tree. getroot () # Get the root element for info in root. findall ('info'): # Find all info elements for child in info: # traverse attributes of each info element and subnode 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.exe cut E ('select * from info'); result = cursor. fetchall () if not result: print 'Please insert the database first 'sys. exit () x = PrettyTable (['IP address', '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' insert statement: ', SQL try: cursor.exe cute (SQL) Statement t: 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.exe cute ('delete from info') conn. commit () conn. close () def main (): parser = argparse. argumentParser () parser. add_argument ('status', type = int, help = "0 clar, 1 read, 2 insert") 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 ()

The fourth job is web programming. You can use the python flask framework to quickly display an xml document. If there are too many files, you will not post them.

Summary

The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, you can leave a message, thank you for your support.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.