向ElementTree生成的XML添加SOAP信封

2024-09-30 08:33:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我从数据库中读取了一些数据,使用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>

Tags: textwebchildtopmsgxmletfunc
2条回答

我后来设法解决了这个问题。在

    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)函数

我的dd = ET.tostring(root, encoding='utf8', method='xml')生成的XML 我刚打电话过来 requests.post(url, data=data.format(d), headers=headers, verify=True)

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的元素名称。传递给ElementSubElement(另一个lxml扩展名)的命名空间映射将该URI映射到前缀,该前缀用于输出:

^{pr2}$

相关问题 更多 >

    热门问题