我从数据库中读取了一些数据,使用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:
^{pr2}$现在,在使用请求将XML发布到web服务之前,我需要将XML封装在SOAP信封中。如何使我的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>
我后来设法解决了这个问题。在
我使用了
.format(d)
函数我的
d
是d = ET.tostring(root, encoding='utf8', method='xml')
生成的XML
我刚打电话过来requests.post(url, data=data.format(d), headers=headers, verify=True)
Python的标准
ElementTree
库不支持CDATA部分,因此需要确保使用的是lxml
。假设您已经将<Enquiry>
元素另存为一个字符串,这将为您提供您要查找的内容:我使用
^{pr2}$QName
函数创建包含名称空间URI的元素名称。传递给Element
和SubElement
(另一个lxml
扩展名)的命名空间映射将该URI映射到前缀,该前缀用于输出:相关问题 更多 >
编程相关推荐