2014-02-06 3 views
-1

Я использую Python для анализа ответа XML с веб-службы SOAP. Customer возвращает около 40 значений, как показано ниже. Я хотел бы знать, есть ли способ сделать это, поэтому мне нужно только ввести одно в свой оператор return и получить все возвращаемые значения? Я попытался использовать for customer in doc.findall('.//Customer').itervalues(), и это не сработало, поскольку я считаю, что вызов для словарей. Те же результаты и аргументы позади .iteritems.Что должно быть в моем возвращении?

doc = ET.fromstring(response_xml) 
for customer in doc.findall('.//Customer'): 
    customer_number = customer.findtext('CustomerNumber') 
    customer_first_name = customer.findtext('FirstName') 
    customer_last_name = customer.findtext('LastName') 
    customer_middle_name = customer.findtext('MiddleName') 
    customer_salutation = customer.findtext('Salutation') 
    customer_gender = customer.findtext('Gender') 
    customer_language = customer.findtext('Language') 
    customer_address1 = customer.findtext('Address1') 
    customer_address2 = customer.findtext('Address2') 
    customer_address3 = customer.findtext('Address3') 
    customer_city = customer.findtext('City') 
    customer_county = customer.findtext('County') 
    customer_state_code = customer.findtext('StateCode') 
    customer_zip_code = customer.findtext('ZipCode') 
    customer_phone_number = customer.findtext('PhoneNumber') 
    customer_business_phone = customer.findtext('BusinessPhone') 
    customer_business_ext = customer.findtext('BusinessExt') 
    customer_fax_number = customer.findtext('FaxNumber') 
    customer_birth_date = customer.findtext('BirthDate') 
    customer_drivers_license = customer.findtext('DriversLicense') 
    customer_contact = customer.findtext('Contact') 
    customer_preferred_contact = customer.findtext('PreferredContact') 
    customer_mail_code = customer.findtext('MailCode') 
    customer_tax_exempt_Number = customer.findtext('TaxExmptNumber') 
    customer_assigned_salesperson = customer.findtext('AssignedSalesperson') 
    customer_type = customer.findtext('CustomerType') 
    customer_preferred_phone = customer.findtext('PreferredPhone') 
    customer_cell_phone = customer.findtext('CellPhone') 
    customer_page_phone = customer.findtext('PagePhone') 
    customer_other_phone = customer.findtext('OtherPhone') 
    customer_other_phone_desc = customer.findtext('OtherPhoneDesc') 
    customer_email1 = customer.findtext('Email1') 
    customer_email2 = customer.findtext('Email2') 
    customer_optional_field = customer.findtext('OptionalField') 
    customer_allow_contact_postal = customer.findtext('AllowContactByPostal') 
    customer_allow_contact_phone = customer.findtext('AllowContactByPhone') 
    customer_allow_contact_email = customer.findtext('AllowContactByEmail') 
    customer_business_phone_ext = customer.findtext('BusinessPhoneExtension') 
    customer_internatinol_bus_phone = customer.findtext('InternationalBusinessPhone') 
    customer_international_cell = customer.findtext('InternationalCellPhone') 
    customer_external_x_reference_key = customer.findtext('ExternalCrossReferenceKey') 
    customer_international_fax = customer.findtext('InternationalFaxNumber') 
    customer_international_other_phone = customer.findtext('InternationalOtherPhone') 
    customer_international_home_phone = customer.findtext('InternationalHomePhone') 
    customer_preferred_name = customer.findtext('CustomerPreferredName') 
    customer_international_pager = customer.findtext('InternationalPagerPhone') 
    customer_preferred_lang = customer.findtext('PreferredLanguage') 
    customer_last_change_date = customer.findtext('LastChangeDate') 
    customer_vehicles = customer.findtext('Vehicles') 
    customer_ccid = customer.findtext('CCID') 
    customer_cccd = customer.findtext('CCCD') 


webservice.close() 
return 

ответ

4

Я хотел бы написать, что в качестве функции генератора уступая dicts, где ключ соответствует findtext аргумент, например:

fields = ['CustomerNumber', 'FirstName', 'LastName', 
      # ... 
     ] 
for customer in doc.findall('.//Customer'): 
    yield dict((f, customer.findtext(f)) for f in fields) 
+0

Видимо, я не могу сделать это решение в 2,7 :( – DarthOpto

+0

Почему не Что ошибка –

+0

'? Python версии <3.3 не позволяют «возвращать» с аргументами внутри генератора – DarthOpto

0

Вы либо хотите вернуть list из dict S:

customers = [] 
for customer in doc.findall('.//Customer'): 
    customer_dict = {} 
    customer_dict['number']  = customer.findtext('CustomerNumber') 
    customer_dict['first_name'] = customer.findtext('FirstName') 
    customer_dict['last_name'] = customer.findtext('LastName') 
    # ad nauseum 
    customers.append(customer_dict) 

webservice.close() 
return customers 

Или вы сделаете Customer класс, который обрабатывает это, и вы возвращаете list экземпляров клиента.

0

Я хотел бы использовать словарь словарей:

doc = ET.fromstring(response_xml) 
customers = {} 
cust_dict = {} 
for customer in doc.findall('.//Customer'): 
    cust_dict['customer_number'] = customer.findtext('CustomerNumber') 
    cust_dict['customer_first_name'] = customer.findtext('FirstName') 
    cust_dict['customer_last_name'] = customer.findtext('LastName') 
    snip snip... 
    customers[customer_number] = cust_dict # or whatever property you want to use to identify each customer, I'm assuming customer_number is some sort of id number   

webservice.close() 
return customers 

То есть, если у вас нет класса вы можете использовать для создания Customer объекта.

Смежные вопросы