gpt4 book ai didi

python-3.x - XML 到 CSV Python

转载 作者:行者123 更新时间:2023-12-05 08:23:06 24 4
gpt4 key购买 nike

状态的 XML 数据 (file.xml) 如下所示

<?xml version="1.0" encoding="UTF-8" standalone="true"?>
<Activity_Logs xsi:schemaLocation="http://www.cisco.com/PowerKEYDVB/Auditing
DailyActivityLog.xsd" To="2018-04-01" From="2018-04-01" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://www.cisco.com/PowerKEYDVB/Auditing">
<ActivityRecord>
<time>2015-09-16T04:13:20Z</time>
<oper>Create_Product</oper>
<pkgEid>10</pkgEid>
<pkgName>BBCWRL</pkgName>
</ActivityRecord>
<ActivityRecord>
<time>2015-09-16T04:13:20Z</time>
<oper>Create_Product</oper>
<pkgEid>18</pkgEid>
<pkgName>CNNINT</pkgName>
</ActivityRecord>

上述 XML 文件的解析和转换为 CSV 将由以下 python 代码完成。

import csv
import xml.etree.cElementTree as ET


tree = ET.parse('file.xml')
root = tree.getroot()


data_to_csv= open('output.csv','w')

list_head=[]

Csv_writer=csv.writer(data_to_csv)

count=0
for elements in root.findall('ActivityRecord'):
List_node = []
if count == 0 :

time = elements.find('time').tag
list_head.append(time)

oper = elements.find('oper').tag
list_head.append(oper)

pkgEid = elements.find('pkgEid').tag
list_head.append(pkgEid)


pkgName = elements.find('pkgName').tag
list_head.append(pkgName)

Csv_writer.writerow(list_head)
count = +1

time = elements.find('time').text
List_node.append(time)

oper = elements.find('oper').text
List_node.append(oper)

pkgEid = elements.find('pkgEid').text
List_node.append(pkgEid)

pkgName = elements.find('pkgName').text
List_node.append(pkgName)

Csv_writer.writerow(List_node)

data_to_csv.close()

我使用的代码没有给我任何 CSV 格式的数据。谁能告诉我到底哪里出了问题?

最佳答案

使用 Pandas,解析所有 xml 字段。

import xml.etree.ElementTree as ET
import pandas as pd

tree = ET.parse("file.xml")
root = tree.getroot()

get_range = lambda col: range(len(col))
l = [{r[i].tag:r[i].text for i in get_range(r)} for r in root]

df = pd.DataFrame.from_dict(l)
df.to_csv('file.csv')

关于python-3.x - XML 到 CSV Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49898661/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com