我已经从数据库中读取了一些数据,使用xml.etree.ElementTree
我可以使用以下代码生成XML:
top = ET.Element("Enquiry")
child = ET.SubElement(top, 'DocumentHeader')
msgid = ET.SubElement(child, 'msgid')
msgid.text = "4444444"
refno = ET.SubElement(child, 'refno')
refno.text = "xxxxxx"
msg_func = ET.SubElement(child, 'msg_func')
msg_func.text = "9"
#...
tree = ET.ElementTree(top)
root = tree.getroot()
data = ET.tostring(root, encoding='utf8', method='xml')
print data
这产生了这个XML:
<Enquiry>
<DocumentHeader>
<msgid></msgid>
<refno>UCR201700043926</refno>
<msg_func>9</msg_func>
<sender>TIS</sender>
<receiver>CPS</receiver>
<version>1</version>
</DocumentHeader>
<DocumentDetails>
<ucr_no>xxxxxxx</ucr_no>
<token>xxxxxx</token>
</DocumentDetails>
</Enquiry>
现在我需要将XML封装在SOAP信封中,然后再使用请求将其发布到Web服务。如何让我的XML看起来像这样:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://webservice.ucr.oga.kesws.crimsonlogic.com/">
<soapenv:Header/>
<soapenv:Body>
<web:ucrValidation>
<arg0><![CDATA[
<UCR_Enquiry>
<DocumentHeader>
<msgid></msgid>
<refno>xxxxxx</refno>
<msg_func>9</msg_func>
<sender>SGI</sender>
<receiver>CPS</receiver>
<version>1</version>
</DocumentHeader>
<DocumentDetails>
<ucr_no>xxx</ucr_no>
<token>xxxxxx</token>
</DocumentDetails>
</UCR_Enquiry>
]]></arg0>
</web:ucrValidation>
</soapenv:Body>
</soapenv:Envelope>
答案 0 :(得分:1)
Python的标准ElementTree
库不支持CDATA部分,因此您需要确保使用lxml
。假设您已将<Enquiry>
元素保存为字符串,这将为您提供您正在寻找的内容:
from lxml import etree as ET
SOAP_NS = 'http://schemas.xmlsoap.org/soap/envelope/'
WEB_NS = 'http://webservice.ucr.oga.kesws.crimsonlogic.com/'
ns_map = {'soapenv': SOAP_NS, 'web': WEB_NS}
env = ET.Element(ET.QName(SOAP_NS, 'Envelope'), nsmap=ns_map)
head = ET.SubElement(env, ET.QName(SOAP_NS, 'Header'), nsmap=ns_map)
body = ET.SubElement(env, ET.QName(SOAP_NS, 'Body'), nsmap=ns_map)
val = ET.SubElement(body, ET.QName(WEB_NS, 'ucrValidation'), nsmap=ns_map)
arg = ET.SubElement(val, 'arg0')
arg.text = ET.CDATA('Here is where you can put your CDATA text!!!')
# now you have XML!
print(ET.tostring(env, pretty_print=True))
我使用QName
函数创建包含名称空间URI的元素名称。传递给Element
和SubElement
(另一个lxml
扩展名)的命名空间映射将该URI映射到用于输出的前缀:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://webservice.ucr.oga.kesws.crimsonlogic.com/">
<soapenv:Header/>
<soapenv:Body>
<web:ucrValidation>
<arg0><![CDATA[Here is where you can put your CDATA text!!!]]></arg0>
</web:ucrValidation>
</soapenv:Body>
</soapenv:Envelope>
答案 1 :(得分:0)
我后来设法解决了这个问题。
data = '''
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://webservice.ucr.oga.kesws.crimsonlogic.com/">
<soapenv:Header/>
<soapenv:Body>
<web:ucrValidation>
<arg0><![CDATA[
{0}
]]></arg0>
</web:ucrValidation>
</soapenv:Body>
</soapenv:Envelope>'''
我使用了.format(d)
函数
我的d
是由XML
生成的d = ET.tostring(root, encoding='utf8', method='xml')
虽然发布我刚刚打电话
requests.post(url, data=data.format(d), headers=headers, verify=True)