如何在python中解析soap响应?

jgovgodb  于 2023-02-06  发布在  Python
关注(0)|答案(1)|浏览(216)

我发现了一些类似的解决方案,但它不适合我。我想知道解析soap响应的最佳实践。
我的源代码是:

from zeep.transports import Transport

response = transport.post_xml(address, payload, headers)
print(type(response))
print(response.content)

输出:

<class 'requests.models.Response'>

b'<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Header/><soap:Body><soap:Fault><faultcode>soap:Server</faultcode><faultstring>UNKNOW_LOCALID</faultstring><detail><ns2:SoapServiceFaultUtilisation xmlns:ns2="http://nps.ideosante.com/"><codeStatus>70</codeStatus><message>Unknown local ID: 1990967085562</message></ns2:SoapServiceFaultUtilisation></detail></soap:Fault></soap:Body></soap:Envelope>'

问题:www.example.com_xml返回字节字符串响应。这使我无法将响应转换为xml格式。transport.post_xml returning bytes string response. Which is make me unable to convert the response to xml format.
我怎样才能从响应中得到codeStatus值?我应该使用哪个简单而最好的库。提前感谢。

nue99wik

nue99wik1#

在这里使用xml.etree.ElementTree
它很容易解析内容和属性。
演示代码

import xml.etree.ElementTree as ET

content = b'<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Header/><soap:Body><soap:Fault><faultcode>soap:Server</faultcode><faultstring>UNKNOW_LOCALID</faultstring><detail><ns2:SoapServiceFaultUtilisation xmlns:ns2="http://nps.ideosante.com/"><codeStatus>70</codeStatus><message>Unknown local ID: 1990967085562</message></ns2:SoapServiceFaultUtilisation></detail></soap:Fault></soap:Body></soap:Envelope>'
print(content)

root = ET.fromstring(content)
print(root.find(".//codeStatus").text)

结果

b'<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Header/><soap:Body><soap:Fault><faultcode>soap:Server</faultcode><faultstring>UNKNOW_LOCALID</faultstring><detail><ns2:SoapServiceFaultUtilisation xmlns:ns2="http://nps.ideosante.com/"><codeStatus>70</codeStatus><message>Unknown local ID: 1990967085562</message></ns2:SoapServiceFaultUtilisation></detail></soap:Fault></soap:Body></soap:Envelope>' 
70

相关问题