首页 > 解决方案 > 如何使用 Python 解析 SOAP WSDL 方法 XML 响应?

问题描述

我正在使用 SOAP WSDL 来获取使用 python suds 库的国家/地区列表。这是python代码。

from suds.client import Client
from suds.wsse import *
base_url = 'https://some_server/ws/CountryListService/CountryListService?wsdl'
client = Client(base_url, username='abc', password='abcd')
cuntrylist = client.service.getCountryList()
print(cuntrylist)

它打印如下。
如何从以下响应中读取/获取 Python 中的 COUNTRYCODE 和 COUNTRYNAME?
如何读取/解析以下内容并将其保存到数据库表中?

(COUNTRYLIST){
 COUNTRY[] = 
  (countryDto){
     COUNTRYCODE = "682"
     COUNTRYNAME = "Saudi Arabia"
  },
  (countryDto){
     COUNTRYCODE = "792"
     COUNTRYNAME = "Turkey"
  },
  (countryDto){
     COUNTRYCODE = "400"
     COUNTRYNAME = "Jordan"
  },
}

cuntrylist 遵循对象类型

print(type(cuntrylist))
<class 'suds.sudsobject.COUNTRYLIST'>

我有许多其他 SOAP WSDL 方法和非常复杂的响应,并且卡住了如何获取值?

标签: pythonparsingsoapwsdlresponse

解决方案


我通过以下方式解决了它。首先将 Suds 对象转换为可序列化的格式。

    def recursive_asdict(self, d):
    """Convert Suds object into serializable format."""
    out = {}
    for k, v in asdict(d).items():
        if hasattr(v, '__keylist__'):
            out[k] = self.recursive_asdict(v)
        elif isinstance(v, list):
            out[k] = []
            for item in v:
                if hasattr(item, '__keylist__'):
                    out[k].append(self.recursive_asdict(item))
                else:
                    out[k].append(item)
        else:
            out[k] = v
    return out

调用 SOAP 服务

client = Client(base_url, username='abc', password='abc')
cuntrylist = client.service.getCountryList()
country_dict = self.recursive_asdict(cuntrylist)
cls = country_dict['COUNTRY']

for item in cls:
   print(item['COUNTRYCODE'], item['COUNTRYNAME'])

推荐阅读