简体   繁体   English

从 Python 响应中的 SOAP 提取 XML 数据

[英]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 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' AttributeError:“无”没有属性“信封”

Below is a sample of my code.下面是我的代码示例。 I'm trying to extract the RequestType value from the below我正在尝试从下面提取RequestType

<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 untangle 的示例使用

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

I've also tried parsed_xml.Envelope.Body.Response.RequestType.cdata我也试过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/':顺便说一句,我认为您的回复不应包含“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.我想你会发现xml.etree库在这种情况下更有用。

import requests
from xml.etree import ElementTree

Then we need to define the namespaces for the SOAP Response然后我们需要为 SOAP 响应定义命名空间

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然后简单地找到所有的 DOM

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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