我想将此格式从xml文件更改为csv。我也想做一个循环,并将所有文件夹xml文件放在一个cvs文件中。
<?xml version="1.0" encoding="UTF-8"?>
<Shot
Shotcode = "30AA"
Id = "1"
ShotDate = "4/2/2000">
<Images>
<Image
ImageNumber="103"
RawFileName="103_Shot.jpg" />
<Image
ImageNumber="104"
RawFileName="104_Shot.jpg" />
<Image
ImageNumber="105"
RawFileName="105_Shot.jpg" />
</Images>
<Metrics>
<Metric
Name = "Hole"
TypeId = "163"
Value = "0" />
<Metric
Name = "Area"
TypeId = "10"
Value = "63" />
</Metrics>
</Shot>
我尝试使用此代码,但是此创建cvs文件时没有循环,并且所有数据均以向下的两列或更多列打印,但我想以行形式显示在一边。
root = tree.getroot()
_30AA = open('30AA.csv', 'w+')
csvwriter = csv.writer(_30AA)
head = []
ShotCode = root.attrib['Shotcode']
csvwriter.writerow(['ShotCode', ShotCode])
head.append(ShotCode)
ShotDate = root.attrib['ShotDate']
csvwriter.writerow(['ShotDate', ShotDate])
for member in root.getchildren():
submembers = member.getchildren()
keys = submembers[0].attrib.keys()
csvwriter.writerow(keys)
for submember in submembers:
row_data = [submember.attrib[k] for k in keys]
csvwriter.writerow(row_data )
_30AA.close()
我希望得到这种结果
ShotCode Id ShotDate ImageNumber RawFileName Name Hole Area
3078 1 4/27/2010 103 103_Shot.jpg TypeID 163 10
104 104_Shot.jpg Value 0 63
105 105_Shot.jpg