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


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)
全栈程序员-站长的头像全栈程序员-站长

相关推荐

  • acwing-171. 送礼物(双向dfs+打标+二分)

    acwing-171. 送礼物(双向dfs+打标+二分)达达帮翰翰给女生送礼物,翰翰一共准备了 N 个礼物,其中第 i 个礼物的重量是 G[i]。达达的力气很大,他一次可以搬动重量之和不超过 W 的任意多个物品。达达希望一次搬掉尽量重的一些物品,请你告诉达达在他的力气范围内一次性能搬动的最大重量是多少。输入格式第一行两个整数,分别代表 W 和 N。以后 N 行,每行一个正整数表示 G[i]。输出格式仅一个整数,表示达达在他的力气范围内一次性能搬动的最大重量。数据范围1≤N≤46,1≤W,G[i]≤231−1输入样例:20 5754

    2022年8月8日
  • delphi 单引号用quotedstr()就是爽

    delphi 单引号用quotedstr()就是爽sp_qry.Close;  sp_qry.SQL.Clear;  sp_qry.SQL.Add(‘select*fromitem_infowhereitem_clsno=’+quotedstr(sp_lb.KeyValue));  sp_qry.Open; 用quotedstr()函数不用去算””个数

    2022年10月9日
  • J2EE是什么意思_main()函数是java程序的执行入口

    J2EE是什么意思_main()函数是java程序的执行入口j2ee   J2EE简介  J2EEJava2平台企业版(Java2Platform,EnterpriseEdition)   J2EE是一套全然不同于传统应用开发的技术架构,包含许多组件,主要可简化且规范应用系统的开发与部署,进而提高可移植性、安全与再用价值。   J2EE核心是一组技术规范与指南,其中所包含的各类组件、服务架构及技术层次,均有共通的标准及规格,让各种依

    2022年10月11日
  • C语言编写简易图书管理系统[通俗易懂]

    C语言编写简易图书管理系统[通俗易懂]1.课程论文题目图书管理系统2.程序设计思路图书管理系统保持记录以进行删除,查询,借书,还书,退出,添加等等操作;使用菜单以实现功能选择模块。3.功能模块图4.数据结构设计1.编写主函数main()2.设计功能选项并标号,用switch选择,然后进入不同模块,进行不同选择,实现不同功能。3.为每个图书信息设置一个结构体,提供查询功能,还有删除功能以及借书还书功能。4.每运行一…

    2022年10月11日
  • pycharm导入anaconda_pip怎么用镜像更新

    pycharm导入anaconda_pip怎么用镜像更新win10设置pip源在下面目录下创建pip文件夹:C:\Users\你的用户名\AppData\Roaming\pip(注意:AppData可能是隐藏文件)进入pip文件夹,新建pip.txt文件输入如下:[global]timeout=6000index-url=http://pypi.douban.com/simpletrusted-host=pypi.douban.com重命名为pip.ini,完成!!附带一些其他源:阿里云http://mi

    2022年8月25日
  • ubuntu桌面主题更换_更换主题的软件

    ubuntu桌面主题更换_更换主题的软件目录一、安装必要的工具二、下载主题三、更换主题一、安装必要的工具为了使下载的主题能应用于Ubuntu,我们必须在Ubuntu上安装几个工具:sudoapt-getupdatesudoapt-getinstallgnome-tweak-toolsudoapt-getinstallgnome-shell-extensions上述第三条命令若执行失败,请读者自行百度解决方案。以上命令执行完成后,我们的Ubuntu就安装了Tweak-tool工具,可以从Ubuntu的管理工具“软件”

    2022年9月16日

发表回复

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

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