【发布时间】:2016-09-02 15:44:53
【问题描述】:
我是第一次使用 Salesforce SOAP API,所以我不熟悉 SOAP 格式问题等。我正在使用 lxml 库生成 XML,但似乎有格式问题。
我收到的错误是:“Envelope 元素的子元素必须是 Header 或 Body 元素”这很奇怪,因为当我查看由 SalesforceLeadConverter.build_xml() 方法生成的 XML 时,它看起来是正确的。这是
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<Header>
<ns0:SessionHeader xmlns:ns0="urn">
<ns0:sessionId>ldfkjskjdfksdfsdfsdf</ns0:sessionId>
</ns0:SessionHeader>
</Header>
<Body>
<ns1:convertLead xmlns:ns1="urn">
<ns1:leadConverts>
<ns1:leadId>00Qj000000PMV3h</ns1:leadId>
<ns1:doNotCreateOpportunity>False</ns1:doNotCreateOpportunity>
<ns1:sendNotificationEmail>False</ns1:sendNotificationEmail>
</ns1:leadConverts>
</ns1:convertLead>
</Body>
</soapenv:Envelope>
这是生成 XML 的完整类和相关方法:
from lxml import etree
class SalesforceLeadConverter(object):
def __init__(self, session_id, lead_id, **kwargs):
""" Provides functionality for converting a Lead to a new or existing
Account and create a new Contact or update an existing Contact.
account_id: Optional; if specified, converts the Lead to a Contact
associated with this Account.
contact_id: Optional; if specified, converts the Lead into an existing
Contact record, preventing the creation of a duplicate.
"""
self.session_id = session_id
self.lead_id = lead_id
self.account_id = kwargs.get('account_id', False)
self.contact_id = kwargs.get('contact_id', False)
self.converted_status = kwargs.get('converted_status', False)
self.do_not_create_opportunity = str(kwargs.get('do_not_create_opportunity', False))
self.opportunity_name = kwargs.get('opportunity_name', False)
self.owner_id = kwargs.get('owner_id', False)
self.send_notification_email = str(kwargs.get('send_notification_email', False))
def build_xml(self):
S_NS = 'http://schemas.xmlsoap.org/soap/envelope/'
S_PRE = '{' + S_NS + '}'
root = etree.Element(S_PRE + 'Envelope', nsmap={'soapenv': S_NS})
soapenv = etree.SubElement(root, 'Header')
header = etree.SubElement(soapenv, '{urn}SessionHeader')
sid = etree.SubElement(header, '{urn}sessionId').text=self.session_id
soapenv2 = etree.SubElement(root, 'Body')
urn2 = etree.SubElement(soapenv2, '{urn}convertLead')
lead_converts = etree.SubElement(urn2, '{urn}leadConverts')
lead_id = etree.SubElement(
lead_converts,
'{urn}leadId'
).text=self.lead_id
do_not_create_opportunity = etree.SubElement(
lead_converts,
'{urn}doNotCreateOpportunity'
).text=self.do_not_create_opportunity
send_notification_email = etree.SubElement(
lead_converts,
'{urn}sendNotificationEmail'
).text=self.send_notification_email
xml_meta = """<?xml version="1.1" encoding="utf-8"?>"""
return xml_meta + etree.tostring(root, encoding='utf-8')
【问题讨论】: