Python-尝试将xml转换为csv时出错

时间:2019-02-28 13:47:53

标签: python xml python-3.x elementtree

我有下面的代码,该代码读取xml文件并尝试将其转换为csv。下面的方法可以正常工作,但是当数据具有另一个子级别时,它将引发错误- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions { int appearCount = [[NSUserDefaults standardUserDefaults] objectForKey: @"appearCount"]; if (appearCount) { [[NSUserDefaults standardUserDefaults] setValue: 1 forKey: @"appearCount"]; } else { if (appearCount + 1 == 2) { // show alert } [[NSUserDefaults standardUserDefaults] setValue: appearCount + 1 forKey: @"appearCount"]; } }

以下是我要使用的数据集:

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

1 个答案:

答案 0 :(得分:1)

下面的代码能够收集您要查找的数据。

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
相关问题