简体   繁体   中英

Extract XML data from SOAP Response in Python

I am using a Python script to receive an XML response from a SOAP web service, and I'd like to extract specific values from the XML response. I'm trying to use the 'untangle' library, but keep getting the following error:

AttributeError: 'None' has no attribute 'Envelope'

Below is a sample of my code. I'm trying to extract the RequestType value from the below

<soap:Envelope
    xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Header/>
    <soap:Body>
        <Response>\n  
            <RequestType>test</RequestType> 
        </Response>
    </soap:Body>
</soap:Envelope>

Sample use of untangle

parsed_xml = untangle.parse(xml)
print(parsed_xml.Envelope.Response.RequestType.cdata)

I've also tried parsed_xml.Envelope.Body.Response.RequestType.cdata

This will solve your problem, assuming you want to extract 'test'. By the way, i think your response should not have 'soap:Header/':

import xmltodict

stack_d = xmltodict.parse(response.content)
stack_d['soap:Envelope']['soap:Body']['Response']['RequestType']

I think you will find the xml.etree library to be more usable in this context.

import requests
from xml.etree import ElementTree

Then we need to define the namespaces for the SOAP Response

namespaces = {
    'soap': 'http://schemas.xmlsoap.org/soap/envelope/',
    'a': 'http://www.etis.fskab.se/v1.0/ETISws',
}

dom = Element.tree.fromstring(response.context)

Then simply find all the DOMs

names = dom.findall('./soap:Body',namespaces)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM