python将xml写入excel,python3读取xml文件,写入excel表

body.xml

C04

1

0000

成功

WDDDwe33455

粤BC9098

01

LB82061102

03

03

20091222

readXmlToExcel.py

#!/usr/bin/python3

#create time: 2020-03-31

import xml.dom.minidom #导入处理xml文件的模块

import pandas as pd

import xlwt

try:

vin_list = []

LicensePlateNo_list = []

LicensePlateType_list = []

LicensePlateType_list = []

EngineNo_list = []

PMVehicleType_list = []

PMUserNature_list = []

IneffectualDate_list = []

#使用minidom解析器打卡xml文档

dom = xml.dom.minidom.parse("body.xml")

#得到文档元素对象

Packet = dom.documentElement #用于得到dom对象的文档元素,并把获得的对象给root

if Packet.hasAttribute("shelf"):

print('Root element: %s' % (Packet.getAttribute("type")))

#获得标签为Body的多组标签

child_tag = Packet.getElementsByTagName("Body")

first_child = child_tag[0]

#车架号

vin_value = first_child.getElementsByTagName('VIN')[0].childNodes[0].data #获得元素属性对应的值

print(vin_value)

vin_list.append(vin_value)

#号牌号码

LicensePlateNo = first_child.getElementsByTagName('LicensePlateNo')[0].firstChild.data

LicensePlateNo_list.append(LicensePlateNo)

#号牌种类代码

LicensePlateType = first_child.getElementsByTagName('LicensePlateType')[0].firstChild.data

LicensePlateType_list.append(LicensePlateType)

#发动机hao

EngineNo = first_child.getElementsByTagName('EngineNo')[0].firstChild.data

EngineNo_list.append(EngineNo)

#交管车辆类型

PMVehicleType = first_child.getElementsByTagName('PMVehicleType')[0].firstChild.data

PMVehicleType_list.append(PMVehicleType)

#车辆使用性质代码

PMUserNature = first_child.getElementsByTagName('PMUserNature')[0].firstChild.data

PMUserNature_list.append(PMVehicleType)

#校验有效日期

IneffectualDate = first_child.getElementsByTagName('IneffectualDate')[0].firstChild.data

IneffectualDate_list.append(IneffectualDate)

#将列表存储为字典

all_dict = {

'VIN':vin_list,

'LicensePlateNo':LicensePlateNo_list,

'LicensePlateType': LicensePlateType_list,

'EngineNo': EngineNo_list,

'PMVehicleType': PMVehicleType_list,

'PMUserNature': PMUserNature_list,

'IneffectualDate': IneffectualDate_list

}

df = pd.DataFrame(all_dict) #将字典转换为DataFrame

#将DataFrame数据写入excel表中

with pd.ExcelWriter('car_table.xls') as Writer:

df.to_excel(Writer,'Sheet1',index=False)

except xml.parsers.expat.ExpatError as e:

print(e)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值