Home > Mobile >  How to parser soap response in python?
How to parser soap response in python?

Time:02-05

I found some similar solution but it's not working for me. I would like to know the best practice of parser the soap response.

My source code is :

from zeep.transports import Transport

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

Output:

<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>'

problem: transport.post_xml returning bytes string response. Which is make me unable to convert the response to xml format.

How can I get the codeStatus value form the response? which simple and best library I should use. Thanks in advance.

CodePudding user response:

Using the xml.etree.ElementTree in here

It easily parse content and attribute.

Demo Code

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)

Result

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
  • Related