簡體   English   中英

Python-嘗試將xml轉換為csv時出錯

[英]Python - Error when trying to convert xml to csv

我有下面的代碼,該代碼讀取xml文件並嘗試將其轉換為csv。 下面的方法工作正常,但是當數據有一個附加子級別時,它將錯誤child index out of range

以下是我要使用的數據集:

<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<Document>
  <Customer>
    <CustomerCode>ABC</CustomerCode>
    <CustomerName>ABC Co</CustomerName>
    <CustomerBusinessHours>
        <CustomerBusinessHoursTimeZoneOffset>1.000000</CustomerBusinessHoursTimeZoneOffset>
    </CustomerBusinessHours>
  </Customer>
</Document>

我嘗試構建的代碼:

import xml.etree.ElementTree as ET
import csv


tree = ET.parse("/users/desktop/sample.xml")
root = tree.getroot()

# open a file for writing

Resident_data = open('/users/desktop/file.csv', 'w')

# create the csv writer object

csvwriter = csv.writer(Resident_data)
resident_head = []

count = 0
for member in root.findall('Customer'):
    resident = []
    address_list = []
    if count == 0:
        CustomerCode = member.find('CustomerCode').tag
        resident_head.append(CustomerCode)
        CustomerName = member.find('CustomerName').tag
        resident_head.append(CustomerName)
        CustomerBusinessHours = member[3].tag
        resident_head.append(CustomerBusinessHours)
        csvwriter.writerow(resident_head)
        count = count + 1

    CustomerCode = member.find('CustomerCode').text
    resident.append(CustomerCode)
    CustomerName = member.find('CustomerName').text
    resident.append(CustomerName)
    CustomerBusinessHours = member[3][1].text
    address_list.append(CustomerBusinessHours)
    CustomerBusinessHoursTimeZoneOffset = member[3][2].text
    address_list.append(CustomerBusinessHoursTimeZoneOffset)
    csvwriter.writerow(resident)
Resident_data.close()

我收到以下錯誤:

CustomerBusinessHours = member[3][1].text
IndexError: child index out of range

預期產量:

CustomerCode,CustomerName,CustomerBusinessHoursTimeZoneOffset
ABC,ABC Co,1.000000

下面的代碼能夠收集您要查找的數據。

import xml.etree.ElementTree as ET

xml = '''<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<Document>
  <Customer>
    <CustomerCode>ABC</CustomerCode>
    <CustomerName>ABC Co</CustomerName>
    <CustomerBusinessHours>
        <CustomerBusinessHoursTimeZoneOffset>1.000000</CustomerBusinessHoursTimeZoneOffset>
    </CustomerBusinessHours>
  </Customer>
</Document>'''

tree = ET.fromstring(xml)
for customer in tree.findall('Customer'):
    print(customer.find('CustomerCode').text)
    print(customer.find('CustomerName').text)
    print(customer.find('CustomerBusinessHours').find('CustomerBusinessHoursTimeZoneOffset').text)

產量

ABC
ABC Co
1.000000

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM