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


相关推荐

  • .ziw文件是什么?如何打开.ziw文件?[通俗易懂]

    .ziw文件是什么?如何打开.ziw文件?[通俗易懂].ziw文件是为知笔记的一种文档格式打开方式:找到为知笔记的官网,下载它的windows安装包即可[缺点:该软件会有一个使用的有效期]打开.ziw文件时,右击选择发送到“为知笔记”,选择相应的文件夹保存即可…

    2022年10月12日
    0
  • 5 tips for using Google Buzz on your phone

    5 tips for using Google Buzz on your phonehttp://googlemobile.blogspot.com/2010/03/5-tips-for-using-google-buzz-on-your.html 

    2022年10月16日
    0
  • Svn服务启动的两种方式

    Svn服务启动的两种方式一、svn服务器启动›cmd命令行启动:vsvnserve-d–r文档仓库路径-d后台执行›-r版本库的根目录二、›Windows服务自动启动利用xp、2000以上的系统自带的工具

    2022年7月3日
    18
  • 死磕Lambda表达式(六):Consumer、Predicate、Function复合

    死磕Lambda表达式(六):Consumer、Predicate、Function复合JDK不仅提供的这些函数式接口,其中一些接口还为我们提供了实用的默认方法,这次我们来介绍一下Consumer、Predicate、Function复合。

    2025年7月5日
    1
  • Excel 宏编程-使用excel宏编写第一个Hello World程序实例演示!

    Excel 宏编程-使用excel宏编写第一个Hello World程序实例演示!先看大屏幕,我要演示的效果就是点击hello按钮,运行我们的宏,输出HelloWorld!第一步首先进入开发工具页签,点击宏,创建一个的宏,我起的名字是hello,点击创建。没有开发工具页签的自行百度。第二步进入了编程界面,我们在中间输入MsgBox(“HelloWorld!”),代表弹出窗口显示里面的内容。第三步写完了我们先保存一下,会弹出一个对话框说让你是否继续保存为xls或xlsx类型,但是没法使用宏,所以点击否然后选择类型为xlsm类型后保存即可。

    2022年6月13日
    41
  • box–shadow_shadowboxing

    box–shadow_shadowboxing今天课堂上有学生问到box-shadow这个属性,那么下面我们就来详细的解说下这个属性它的用法,box-shadow是css3中的一个属性,它可以向框添加一个或多个阴影。首先我们来看它的语法:bo

    2022年8月4日
    5

发表回复

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

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