python解析XML文件并转存到excel「建议收藏」

python解析XML文件并转存到excel「建议收藏」python解析XML文件并转存到excel转换前的xml文档信息如下:处理后的效果如下:python代码如下:importxml.saxfromopenpyxlimportWorkbook,load_workbookimportosdefwrite_to_excel(two_dimension_list):path=os.path.dirname(os.path.realpath(__file__))#gettheparentpathofc

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

python解析XML文件并转存到excel

转换前的xml文档信息如下:
处理前的xml文件处理后的效果如下:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
python代码如下:

import xml.sax
from openpyxl import Workbook, load_workbook
import os

def write_to_excel(two_dimension_list):
    path = os.path.dirname(os.path.realpath(__file__))  # get the parent path of current file
    try:
        wb = load_workbook(path+"\\orderfile.xlsx") # load an existing workbook
        ws = wb.create_sheet()
    except:
        wb = Workbook() # create a new workbook
        ws = 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 = tag
        if tag == "orderData":
            self.dic_orderdata['orderId'] = attributes.get('orderId')   # 用 get 方法,如果该键值对不存在会返回None
            self.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__"):
    # 创建一个 XMLReader
    parser = xml.sax.make_parser()
    # 关闭命名空间
    parser.setFeature(xml.sax.handler.feature_namespaces, 0)
    # 重写 ContextHandler
    Handler = 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')
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/171958.html原文链接:https://javaforall.net

(0)
上一篇 2022年8月22日 下午5:00
下一篇 2022年8月22日 下午5:16


相关推荐

  • discuz php接口文档,Discuz二次开发手册.doc[通俗易懂]

    discuz php接口文档,Discuz二次开发手册.doc[通俗易懂]Discuz二次开发手册Discuz文件说明,有助于discuz爱好者,进行自己的开发,在这里提供方便admincp.php——后台系统设置主程序文件,一般只处理菜单的显示的访问权限,不处理管理控制。ajax.php——论坛模板的ajax判断及数据返回都在这里进行attachment.php——附件文件,仅仅处理附件下载的功能。announcement.php——论坛公告的显示,一般很少改con…

    2022年5月19日
    43
  • 什么是Web 2.0——下一代软件的设计模式和商业模式 (全文翻译—1 博客版序)

    什么是Web 2.0——下一代软件的设计模式和商业模式 (全文翻译—1 博客版序)这篇文章,是经O’Reilly公司的TimO’Reilly先生授权后,进行全文翻译、出版的。包括:杂志节选版和网络全文版。转载:请遵循CC版权,保留原文作者和翻译作者信息,以及文章链接。感谢:互联网周刊的李洋提供了许多建议。几个文章版本链接:英文原文:http://www.oreillynet.com/pub/a/oreilly/tim/news/2005/09/30/

    2022年7月21日
    15
  • 状态模式state_解释器模式

    状态模式state_解释器模式状态模式 State动机模式定义实例结构要点总结笔记动机在软件构建过程中,某些对象的状态如果改变,其行为也会随之而发生变化,比如文档处于只读状态,其支持的行为和读写状态支持的行为就可能不同.如何在运行时根据对象的状态来透明地更改对象的行为?而不会为对象操作和状态转换之间引入紧耦合模式定义允许一个对象在其内部状态改变时改变它的行为.从而使对象看起来似乎修改了其行为.从而使对象看起来似乎修改了其行为.从而使对象看起来似乎修改了其行为.实例朴素根据状态来执行下一步enum NetworkStat

    2022年8月9日
    7
  • Android ImageButton(图片按钮)

    Android ImageButton(图片按钮)效果图 图 1 图 2 activity main xml xmlversion 1 0 encoding utf 8

    2026年3月16日
    3
  • ubuntu 安装 windows 字体 美化

    ubuntu 安装 windows 字体 美化

    2021年4月29日
    147
  • 数据挖掘复习(包括一些课本习题)[通俗易懂]

    数据挖掘复习(包括一些课本习题)[通俗易懂]第一章1.数据挖掘定义 在大量的数据中提取潜在有用的信息的过程2.任务分类,聚类,关联,离群点3.对象孔家数据库,时间序列数据库,流数据,多媒体数据库,文本数据,万维网4.知识发现(1)数据清洗(2)数据集成(3)数据转换(4)数据挖掘(5)模式评估(6)知识表示第二章(1)数据挖掘中使用的数据是数据对象及其属性的集合,属性为对象的特性(1)类属性和数值属性,标称,序数,区间,比例数据预处理(1)数据清理(2)数据集成(3)数据变换(4)数据规约(5)离

    2022年5月28日
    31

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号