软硬件环境

  • Ubuntu 15.10 32bit
  • Python 3.5.1
  • PyQt 5.5.1

前言

Python解析XML的方法挺多,本文主要是利用ElementTree来完成。

实例讲解

解析XML

以如下的XML文件为例

<root>
<version>1.0.04</version>
<mysqlhost>10.10.10.240</mysqlhost>
<mysqlport>3306</mysqlport>
<mysqluser>root</mysqluser>
<mysqlpassword>123456</mysqlpassword>
<mysqldatabase>longjingdb</mysqldatabase>
<mysqltable>mac</mysqltable>
<mysqlstbtype>L6000</mysqlstbtype>
<irdetokeytype>1</irdetokeytype>
<printerhost>192.168.1.51</printerhost>
<printerport>4001</printerport>
</root>

编写了一个类来解析,用一个字典来存放

class SYSXMLParser(object):
def __init__(self,file):
self.xmlFile = file
self.sysXMLDict = {} def getSysXMLDict(self):
tree = ET.parse(self.xmlFile)
root = tree.getroot() for child in root.getchildren():
self.sysXMLDict[child.tag] = child.attrib
self.sysXMLDict[child.tag] = child.text return self.sysXMLDict

执行后打印的结果如下

{'mysqlstbtype': 'L6000', 'mysqlpassword': '123456', 'version': '1.0.04', 'printerhost': '192.168.1.51', 'printerport': '4001', 'mysqltable': 'mac', 'mysqldatabase': 'longjingdb', 'mysqlport': '3306', 'mysqluser': 'root', 'mysqlhost': '10.10.10.240', 'irdetokeytype': '1'}

创建XML

手头上刚好有个实例,提供一个文件夹,里面是一些烧录镜像文件,针对这个镜像文件夹,需要生成一个XML文件,XML指定各个镜像文件的名字、对应烧录的地址、还有镜像的路径和md5值。

# -*- coding: utf-8 -*-
__author__ = 'djstava@gmail.com' import os
import sys
import xml.etree.ElementTree as ET from common.constant import *
from checksum.md5 import * FirstRoundImages = {'pmp.toc':PMP_ADDRESS,'secboot.toc':SECBOOT_ADDRESS,'secos.toc':SECOS_ADDRESS,'secosbak.toc':SECOS_BACK_ADDRESS,
'u-boot.toc':UBOOT_ADDRESS,'u-bootbak.toc':UBOOT_BACK_ADDRESS,'splash.dat':SPLASH_ADDRESS} SecondRoundImages = {'factorytest.img':FACTORYTEST_ADDRESS,'boot.img':BOOT_ADDRESS,'system.img':SYSTEM_ADDRESS,'dvbdata.img':DVBDATA_ADDRESS,
'userdata.img':USERDATA_ADDRESS,'cache.img':CACHE_ADDRESS,'otaloader.img':OTALOADER_ADDRESS,'iploader.img':IPLOADER_ADDRESS,
'recovery.img':RECOVERY_ADDRESS} class GenerateConfigXML(object):
firstRoundImageDict = {}
secondRoundImageDict = {} def __init__(self,path):
self.path = path def buildConfigXML(self):
'''
:param path: images dir
:return:
''' self.listDir(self.path) root = ET.Element("root") self.firstRound = ET.SubElement(root,"FirstRound")
for image in self.firstRoundImageDict.keys():
if image == "pmp.toc":
imagePmp = ET.SubElement(self.firstRound,image)
imagePmp.set("name",image)
imagePmp.set("address",self.firstRoundImageDict[image])
imagePmp.set("path",os.path.relpath(self.path + "/" + image))
imagePmp.set("md5",CalcMD5.calcFileMd5(self.path + "/" + image))
self.firstRoundImageDict.pop(image)
break for image in self.firstRoundImageDict.keys():
if image == "secboot.toc":
imagePmp = ET.SubElement(self.firstRound,image)
imagePmp.set("name",image)
imagePmp.set("address",self.firstRoundImageDict[image])
imagePmp.set("path",os.path.relpath(self.path + "/" + image))
imagePmp.set("md5",CalcMD5.calcFileMd5(self.path + "/" + image))
self.firstRoundImageDict.pop(image)
break for image in self.firstRoundImageDict.keys():
if image == "secos.toc":
imagePmp = ET.SubElement(self.firstRound,image)
imagePmp.set("name",image)
imagePmp.set("address",self.firstRoundImageDict[image])
imagePmp.set("path",os.path.relpath(self.path + "/" + image))
imagePmp.set("md5",CalcMD5.calcFileMd5(self.path + "/" + image))
self.firstRoundImageDict.pop(image)
break for image in self.firstRoundImageDict.keys():
if image == "secosbak.toc":
imagePmp = ET.SubElement(self.firstRound,image)
imagePmp.set("name",image)
imagePmp.set("address",self.firstRoundImageDict[image])
imagePmp.set("path",os.path.relpath(self.path + "/" + 'secos.toc'))
imagePmp.set("md5",CalcMD5.calcFileMd5(self.path + "/" + 'secos.toc'))
self.firstRoundImageDict.pop(image)
break for (name,address) in self.firstRoundImageDict.items():
if name == "pmp.toc":
continue if name == "u-bootbak.toc":
imageName = ET.SubElement(self.firstRound,name)
imageName.set("name",name)
imageName.set("address",address)
imageName.set("path",os.path.relpath(self.path + "/u-boot.toc"))
imageName.set("md5",CalcMD5.calcFileMd5(self.path + "/u-boot.toc"))
continue imageName = ET.SubElement(self.firstRound,name)
imageName.set("name",name)
imageName.set("address",address)
imageName.set("path",os.path.relpath(self.path + "/" + name))
imageName.set("md5",CalcMD5.calcFileMd5(self.path + "/" + name)) self.secondRound = ET.SubElement(root,"SecondRound")
for (name,address) in self.secondRoundImageDict.items():
imageName = ET.SubElement(self.secondRound,name)
imageName.set("name",name)
imageName.set("address",address)
imageName.set("path",os.path.relpath(self.path + "/" + name))
imageName.set("md5",CalcMD5.calcFileMd5(self.path + "/" + name)) tree = ET.ElementTree(root)
self.indent(root) if os.path.exists(XML_CONFIG_FILE):
os.remove(XML_CONFIG_FILE) tree.write("config.xml") def listDir(self, path):
for root,dirs,files in os.walk(path):
for file in files:
if file in FirstRoundImages.keys():
print("firstRound: " + file)
if file == 'secos.toc':
self.firstRoundImageDict[file] = FirstRoundImages[file]
self.firstRoundImageDict['secosbak.toc'] = FirstRoundImages['secosbak.toc']
continue if file == 'u-boot.toc':
self.firstRoundImageDict[file] = FirstRoundImages[file]
self.firstRoundImageDict['u-bootbak.toc'] = FirstRoundImages['u-bootbak.toc']
continue self.firstRoundImageDict[file] = FirstRoundImages[file] if file in SecondRoundImages.keys():
print("secondRound: " + file)
self.secondRoundImageDict[file] = SecondRoundImages[file] def indent(self, elem, level=0):
i = "\n" + level*" "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
for e in elem:
self.indent(e, level+1)
if not e.tail or not e.tail.strip():
e.tail = i
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i return elem if __name__ == '__main__':
if len(sys.argv) < 2:
print("Usage: python3 generateConfigXml.py dirOfTheImages")
sys.exit(1) obj = GenerateConfigXML(sys.argv[1])
obj.buildConfigXML()

最后生成的config.xml内容如下:

<root>
<FirstRound />
<SecondRound>
<factorytest.img address="otaloaderbak" md5="2bca7c24acf471ad4126e63224b117c3" name="factorytest.img" path="factory20160411/factorytest.img" />
<iploader.img address="iploader" md5="40d6bf4fe05bb4ce2d500464d48da5a4" name="iploader.img" path="factory20160411/iploader.img" />
<boot.img address="boot" md5="b1937b921ee1122f1946dcb96811e69e" name="boot.img" path="factory20160411/boot.img" />
<system.img address="system" md5="12fe7f8c8920c18a3cc9a815f201cca7" name="system.img" path="factory20160411/system.img" />
<otaloader.img address="otaloader" md5="0831e96caf91482dbb9efde1ca29d3bd" name="otaloader.img" path="factory20160411/otaloader.img" />
<userdata.img address="userdata" md5="536d084f75a46470f2373e3052d288dc" name="userdata.img" path="factory20160411/userdata.img" />
</SecondRound>
</root>

最后顺便提供下python3下的MD5计算方法,见下面这个类

# -*- coding: utf-8 -*-
__author__ = 'djstava@gmail.com' import hashlib class CalcMD5(object):
def __init__(self):
pass @classmethod
def calcFileMd5(self,filePath):
'''
:param filePath:
:return: file checksum value
''' md5 = hashlib.md5() fp = open(filePath,'rb')
md5.update(fp.read()) while True:
block = fp.read(1048576)
if not block:
break
md5.update(block) fp.close()
return md5.hexdigest() @classmethod
def calcStringMd5(self,str):
'''
:param str:
:return: string checksum value
''' return hashlib.md5(str.encode("utf-8")).hexdigest()

python3解析XML文件的更多相关文章

  1. Python3 解析XML 层序遍历二叉树

    Python3 解析XML 层序遍历二叉树 keyword : python3, xml, xml.dom.minidom, 层序遍历, 层次遍历, 二叉树 part1 问题描述 面对如下 XML 文 ...

  2. Android 解析XML文件和生成XML文件

    解析XML文件 public static void initXML(Context context) { //can't create in /data/media/0 because permis ...

  3. JAVA使用SAX解析XML文件

    在我的另一篇文章(http://www.cnblogs.com/anivia/p/5849712.html)中,通过一个例子介绍了使用DOM来解析XML文件,那么本篇文章通过相同的XML文件介绍如何使 ...

  4. JAVA中使用DOM解析XML文件

    XML是一种方便快捷高效的数据保存传输的格式,在JSON广泛使用之前,XML是服务器和客户端之间数据传输的主要方式.因此,需要使用各种方式,解析服务器传送过来的信息,以供使用者查看. JAVA作为一种 ...

  5. java中采用dom4j解析xml文件

    一.前言 在最近的开发中用到了dom4j来解析xml文件,以前听说过来解析xml文件的几种标准方式:但是从来的没有应用过来,所以可以在google中搜索dmo4j解析xml文件的方式,学习一下dom4 ...

  6. XML:使用DOM技术解析xML文件中的城市,实现select级联选择

    中国的城市xml格式:cities.xml <?xml version="1.0" encoding="utf-8"?> <china> ...

  7. dom4j如何解析XML文件

    最近在 一些对xml文件的操作,下面简单写一个dom4j解析xml文件并将其封装到一个javabean中的例子,只是具有针对性的,不是通用的,仅供参考哦~~ 首先说:dom4j是一个java的XML ...

  8. java解析XML文件

    dom4j是一个Java的XML API,类似于jdom,用来读写XML文件的.dom4j是一个非常非常优秀的Java XML API,具有性能优异.功能强大和极端易用使用的特点,同时它也是一个开放源 ...

  9. Android开发学习---使用XmlPullParser解析xml文件

    Android中解析XML的方式主要有三种:sax,dom和pull关于其内容可参考:http://blog.csdn.net/liuhe688/article/details/6415593 本文将 ...

随机推荐

  1. linux-锁屏时间设置

    系统:ubuntu16.04 操作步骤 设置setting -> System Settings -> Brightness&lock, 在界面中选择想要的设置即可: 参考 1.百 ...

  2. Python3中 sys.argv的用法

    sys.avgr 是一个Python的引用模块.刚好做一个作业需要用到它,在sublime上编辑后运行,试图从结果发现它的用途,然而结果一直都是没结果. 后面在网上查了资料,才明白过来.sys.arg ...

  3. JS Array.filter()方法

    1.filter()接收的函数可以有多个参数.通常我们只使用第一个参数,第二参数和第三个参数表示元素的位置和数组本身: //去重 var arr = ["1", "2&q ...

  4. USB gadget 驱动 printer.c 分析

    1. modprobe g_printer idVendor=0x0525 idProduct=0xa4a8 modprobe后面也可以加模块参数 2. prn_example从stdout获取数据然 ...

  5. 开源泛域名服务xip.io部署试用

    xip.io 是一个很方便的泛域名服务,类似的有一个xip.name 的开源实现 下载 go get github.com/peterhellberg/xip.name 启动 二进制包在GOPATH/ ...

  6. gridview 自动序号 合计

    第一种方式,直接在Aspx页面GridView模板列中.这种的缺点是到第二页分页时又重新开始了. <asp:TemplateField HeaderText="序号" Ins ...

  7. IBM DS存储存储性能调优

    版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/jaminwm/article/details/26458791 ibm存储适用,其它存储有相似參数. ...

  8. TensorFlow笔记-08-过拟合,正则化,matplotlib 区分红蓝点

    TensorFlow笔记-08-过拟合,正则化,matplotlib 区分红蓝点 首先提醒一下,第7讲的最后滑动平均的代码已经更新了,代码要比理论重要 今天是过拟合,和正则化,本篇后面可能或更有兴趣, ...

  9. 理解JAVA虚拟机(下)

    2016-04-18 20:40:59 三.JVM内存参数调整及监控 3.1  JVM之内存调整 JVM运行时数据区的内存大小可以通过参数来设置,通常能设置的两块区域为堆空间和持久代(方法区),设置方 ...

  10. RTSP HTTP RTP RTCP

    RTSP简介 RTSP(Real Time Streaming Protocol)是由Real Network和Netscape共同提出的如何有效地在IP网络上传输流媒体数据的应用层协议.RTSP对流 ...