python解析XML文件并转存到excel

转换前的xml文档信息如下:
处理后的效果如下:



python代码如下:

import xml.sax
from openpyxl import Workbook, load_workbook
import osdef write_to_excel(two_dimension_list):path = os.path.dirname(os.path.realpath(__file__))  # get the parent path of current filetry:wb = load_workbook(path+"\\orderfile.xlsx") # load an existing workbookws = wb.create_sheet()except:wb = Workbook() # create a new workbookws = wb.create_sheet()for c in range(len(two_dimension_list)):for r in range(len(two_dimension_list[c])):ws.cell(r+1,c+1).value = two_dimension_list[c][r]wb.save(path+"\\orderfile.xlsx")class OrderFileHandler(xml.sax.ContentHandler):def __init__(self):self.CurrentData=""self.dic_orderdata = {}self.dic_fileInfo = {}self.op_code = []self.list_optioncode = []self.list_orderdata = []self.list_fileInfo = []# 文档启动时调用def startDocument(self):print("XML file parse start!")# 遇到XML开始标签时调用,tag 是标签的名字,attributes 是标签的属性值字典def startElement(self,tag,attributes):self.CurrentData = tagif tag == "orderData":self.dic_orderdata['orderId'] = attributes.get('orderId')   # 用 get 方法,如果该键值对不存在会返回Noneself.dic_orderdata['longVIN'] = attributes.get('longVIN')self.dic_orderdata['shortVIN'] = attributes.get('shortVIN')self.dic_orderdata['dummy'] = attributes.get('dummy')   # 不存在于 xml 文件中self.dic_orderdata['softwareLevel'] = attributes.get('softwareLevel')self.list_orderdata.append(list(self.dic_orderdata.values()))print(self.dic_orderdata)elif tag == 'fileInfo':self.dic_fileInfo['date'] = attributes.get('date')self.dic_fileInfo['comment'] = attributes.get('comment')self.dic_fileInfo['author'] = attributes.get('author')self.dic_fileInfo['plantId'] = attributes.get('plantId')self.dic_fileInfo['firstCreationDate'] = attributes.get('firstCreationDate')self.dic_fileInfo['latestCreationDate'] = attributes.get('latestCreationDate')self.dic_fileInfo['vehicleState'] = attributes.get('vehicleState')self.list_fileInfo.append(list(self.dic_fileInfo.values()))# 元素结束调用def endElement(self, tag):if self.CurrentData == "optionCode":self.op_code.append(self.optionCode)self.CurrentData = ""# 读取标签之间的字符时调用def characters(self, content):if self.CurrentData == "optionCode":self.optionCode = content# 解析器到达文档结尾时调用         def endDocument(self):self.list_orderdata.insert(0,list(self.dic_orderdata.keys()))self.list_fileInfo.insert(0,list(self.dic_fileInfo.keys()))self.list_optioncode.insert(0,['optionCode'])self.list_optioncode.insert(1,self.op_code)print("file parse success!")if (__name__ == "__main__"):# 创建一个 XMLReaderparser = xml.sax.make_parser()# 关闭命名空间parser.setFeature(xml.sax.handler.feature_namespaces, 0)# 重写 ContextHandlerHandler = OrderFileHandler()parser.setContentHandler(Handler)parser.parse("C:/Users/Administrator/Desktop/file/A0000000.xml")print(Handler.list_optioncode)write_to_excel(Handler.list_orderdata)write_to_excel(Handler.list_fileInfo)write_to_excel(Handler.list_optioncode)

如果xml文件较大,涉及到的属性比较多,人工敲代码也比较耗费时间。可以使用以下代码实现代码内容转换。

import os , sys , re# 在代码文件相同目录下创建一个test.txt的文件,并将需要转换的xml片段粘贴到该文件中。并根据需要更改str_statement内容。
def generate_code():file = os.path.dirname(os.path.realpath(__file__))+"\\test.txt"with open(file,'a+') as f:f.seek(0,0) # 将指针放到文件其实位置line = str(f.readlines())key = re.findall(r'\s(\w*)=',line)print(key)for item in range(len(key)):attrs = key[item]str_statement = "self.dic_fileInfo['"+attrs+"'] = attributes.get('"+attrs+"')"+'\n'f.write(str_statement)generate_code()

转换后的test.txt文件内容如下:

<fileInfo date="20170720065220" comment="RESERVED" author="system" plantId="gcdm" firstCreationDate="2017-07-20T06:52:20+08:00" latestCreationDate="2027-07-20T06:52:00+08:00" vehicleState="6300">##上面是代码执行前加入的内容,下面是代码执行后追加的内容##self.dic_fileInfo['date'] = attributes.get('date')
self.dic_fileInfo['comment'] = attributes.get('comment')
self.dic_fileInfo['author'] = attributes.get('author')
self.dic_fileInfo['plantId'] = attributes.get('plantId')
self.dic_fileInfo['firstCreationDate'] = attributes.get('firstCreationDate')
self.dic_fileInfo['latestCreationDate'] = attributes.get('latestCreationDate')
self.dic_fileInfo['vehicleState'] = attributes.get('vehicleState')

python解析XML文件并转存到excel相关推荐

  1. python解析xml文件最好选用的模块_用Python解析XML文件

    本文翻译自:https://developer.yahoo.com/python/python-xml.html 使用Python解析XML文件 许多YDN APIs提供了JSON格式的数据输出,JS ...

  2. python读取xml标注坐标_遍历文件 创建XML对象 方法 python解析XML文件 提取坐标计存入文件...

    XML文件??? xml即可扩展标记语言,它可以用来标记数据.定义数据类型,是一种允许用户对自己的标记语言进行定义的源语言. 里面的标签都是可以随心所欲的按照他的命名规则来定义的,文件名为roi.xm ...

  3. python 解析xml 文件: SAX方式

    环境 python:3.4.4 准备xml文件 首先新建一个xml文件,countries.xml.内容是在python官网上看到的. <?xml version="1.0" ...

  4. python解析xml文件选用模块_Python标准库系列之xml模块

    Python's interfaces for processing XML are grouped in the xml package. 带分隔符的文件仅有两维的数据:行和列.如果你想在程序之间交 ...

  5. python解析xml文件选用模块_python语言解析xml文件的常用的有两种方式

    MiniDom方式解析xml xml文件以data.xml为例,具体操作如下: data.xml: 保存用户的信息 Jordy 12345678 20 男 上网 功夫 34443678 18 男 功夫 ...

  6. python解析xml文件最好选用的模块_python高级编程 之解析XML文件模块

    XML是啥?可扩展标记语言(extensible  makeup language),以.xml为后缀的文件. XML文件最大的作用在于存储和传输数据.很多Python的项目就是把产品相关配置参数存储 ...

  7. python解析XML文件报错 entity not defined Entity ndash not defined

    报错 在处理数据集时需要解析xml文件获取需要的数据,一开始采用python自带的xml模块来做,即xml.dom.minidom,然后报错 entity not defined 也没显示是在xml文 ...

  8. python解析xml文件elementtree_在python中使用ElementTree解析xml文件

    ElementTree是python自带的处理xml格式文件的模块,位于libxmletreeElementTree.py.这个模块有两个基本概念:Element和ElementTree. 表示整个树 ...

  9. python解析xml文件elementtree_Python中使用ElementTree解析XML示例

    [XML基本概念介绍] XML 指可扩展标记语言(eXtensible Markup Language). XML 被设计用来传输和存储数据. 概念一: 复制代码 代码如下: # foo元素的起始标签 ...

  10. Python解析XML文件

    今天学习如何利用Python来解析XML文档. 给定一个XML文件,现在我们用Python来提取里面的内容. <deals><data><deal><deal ...

最新文章

  1. Android中XML的命名空间、自定义属性
  2. Xianfeng轻量级Java中间件平台:用户管理
  3. 生活中的实验 —— 磁铁的使用
  4. miui11禁止更新方法
  5. boost::boyer_myrvold_params::kuratowski_subgraph用法的测试程序
  6. datatable 导入mysql 解决_将DataTable中的数据导入到数据库中
  7. xampp安装后apache(端口占用)/mysql无法打开(Attempting to start MySQL service...)/Mysql无法修改端口
  8. C#使用正则表达式检测数字 char 和韩文
  9. 矩池云怎么上传文件夹
  10. linux mysql web界面吗_Linux下安装MySQL Web 管理工具phpMyAdmin
  11. 【总结】大规模数据测试,数据准备时需要注意的问题(【保护已有数据】【大规模数据影响普通测试】【不要着急删除数据】)
  12. configure:3855: gcc -V 5 gcc: error: unrecognized command line option '-V'
  13. ReactNative配合node.js实现的公司通讯录管理app
  14. 数据治理之元数据管理实践
  15. 概率论与数理统计中基于有限样本推断总体分布的方法,基于总体未知参数区间估计的假设检验方法之讨论,以及从数理统计视角重新审视线性回归函数本质...
  16. java中如何添加画板背景图,几何画板中如何添加背景图片
  17. 计算机应用基础实训教程侯冬梅,计算机应用基础实训教程
  18. 旷视回顾全球十大AI治理事件,技术与伦理安全如何进行落地
  19. 强生单剂量新冠疫苗对德尔塔变异病毒有效并可提供持久保护效力
  20. C++学习系列---读取文件名存入txt和从txt读取每行信息

热门文章

  1. Java小白入门:聊聊Java这门编程语言
  2. 记一次 ORA-600 [12700] 故障案例
  3. 内网神器cobaltstrike使用教程
  4. Matlab 终止正在运行的程序
  5. Linux软件安装及修改软件源
  6. 基于51单片机模拟交通灯程序
  7. JavaScript高级程序设计学习总结一
  8. Intellij IDEA中程序播放音乐 没声音
  9. 基于javaweb的旅游管理系统旅行平台(springboot+ssm)
  10. Python大数据处理方案