如何使用 Python ElementTree、LXML 或类似库创建 soap 请求

How to create a soap request using Python ElementTree, LXML or similar library

我正在尝试使用来自 excel sheet 的数据创建 XML SOAP 请求。目前,我使用了 mako 模板,但它需要 XML 模板。如何使用如下命名空间创建请求(这只是一个小示例,并非完整示例 XML):

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mes="http://www.orange.com/Webalc/Interfaces/ManageSupplierQuote/RequestForQuotation/v3/message">
   <soapenv:Header/>
   <soapenv:Body>
      <mes:CalculateSupplierQuote>
         <!--1 to 500 repetitions:-->
         <SupplierQuote>
            <local_circuittype>Existing circuit</local_circuittype>
            <local_businessOpportunity>Access to Orange Business Services Network</local_businessOpportunity>
            <local_accessType>Upgrade/downgrade of full path diversity</local_accessType>
            <!--Optional:-->
            <local_configurationSite>single</local_configurationSite>

通过使用 lxml 库,我能够取得一些进展,但后来我被卡住了。下面是我创建的代码。

from lxml import etree
import lxml.etree
import lxml.builder


Envelope = etree.Element("{http://www.w3.org/1999/soapenv}xmlns")
body = etree.SubElement(Envelope, "{http://www.w3.org/1999/soapenv}body")

print(etree.tostring(Envelope, pretty_print=True))

您构建的 Envelope 元素有误。 etree.Element 的构造函数接收要创建的 xml 元素的(完全限定的)名称(a.k.a 标记),它在您的案例 信封.

将第一行改为:

envelope = etree.Element("{http://www.w3.org/1999/soapenv}Envelope")