如何使用python(在行中)将xml转换为csv文件?

2024-05-16 13:57:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在cvs中对这个xml文档进行编码。我试过了,但没用。我不知道我做错了什么。我对这个很陌生。你知道吗

有一个xml我想转换

<?xml version="1.0" encoding="UTF-8"?> 
<Shot 
  Shotcode = "30AA" 
  ShotDate = "4/2/2000"> 

 <Images> 

  <Image 
   ImageNumber="103" 
   RawFileName="18_Shot_30AA.jpg" /> 
  <Image 
   ImageNumber="104"  
   RawFileName="17_Shot_30AA.jpg" /> 
  <Image 
   ImageNumber="105" 
   RawFileName="14_Shot_30AA" /> 
 </Images> 

 <Metrics> 
  <Metric 
   Name = "30AA" 
   TypeId = "163" 
   Value = "0" /> 

 <Metric 
  Name = "Area" 
  TypeId = "10" 
  Value = "63" /> 
 </Metrics> 

</Shot>

我以这种形式编写这个代码,是为了完成一些示例,并不是完整的程序,而是显示我在做什么。你知道吗

import xml.etree.ElementTree as ET
import csv

tree = ET.parse("30AA.xml")
root = tree.getroot()

30AA = open('30AA.csv', 'w+')
csvwriter = csv.writer(30AA)
head = []

count = 0   #loops
for member in root.findall('Shot'):
Shot = []
if count == 0:
    ShotCode = member.find('ShotCode').tag
    head.append(ShotCode)
    ShotDate = member.find('ShotDate').tag
    head.append(ShotDate)
    csvwriter.writerow(head)
    count = count + 1   
ShotCode = member.find('ShotCode').txt
Shot.append(ShotCode)
ShotDate = member.find('ShotDate').txt
Shot.append(ShotDate)   
30AA.close()

我期望的结果是

Shotcode    30AA    
ShotDate    4/2/2000    

Imagen  103 

Imagen  104 

Imagen  105 

Name TypeId Value
30AA  163   0
area  10    63

Tags: nameimagevaluecountxmlfindheadmember
1条回答
网友
1楼 · 发布于 2024-05-16 13:57:37

好吧,我想我知道哪里出了问题,主要的问题是在读取xml时,它看起来就像是一个csv的东西。你知道吗

xml的根是Shot标记,因此不能使用根.findall('Shot')获取所有标签,因为root已经存在,而且它里面没有任何Shot。 这就是为什么你的输出没有得到任何东西。你知道吗

另外,当您想获取标记的属性时,您可以使用.attrib['name\u of\u attribute']作为示例,而不是成员.查找('ShotCode')。标记应为成员.attrib['ShotCode']

这会对脚本的其余部分产生很大的变化,但接下来需要执行以下操作:

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])
# member is going to be the <Images> and <Metrics>
for member in root.getchildren():

    submembers = member.getchildren()
    # Write the names of the attributes as headings
    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()

会给你想要的

相关问题 更多 >