python - 如何用 Python 解析 SOAP XML?

标签 python xml python-3.x soap zeep

目标: 获取<Name>里面的值标签并打印出来。 下面是简化的 XML。

<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soap:Body>
      <GetStartEndPointResponse xmlns="http://www.etis.fskab.se/v1.0/ETISws">
         <GetStartEndPointResult>
            <Code>0</Code>
            <Message />
            <StartPoints>
               <Point>
                  <Id>545</Id>
                  <Name>Get Me</Name>
                  <Type>sometype</Type>
                  <X>333</X>
                  <Y>222</Y>
               </Point>
               <Point>
                  <Id>634</Id>
                  <Name>Get me too</Name>
                  <Type>sometype</Type>
                  <X>555</X>
                  <Y>777</Y>
               </Point>
            </StartPoints>
         </GetStartEndPointResult>
      </GetStartEndPointResponse>
   </soap:Body>
</soap:Envelope>

尝试:

import requests
from xml.etree import ElementTree

response = requests.get('http://www.labs.skanetrafiken.se/v2.2/querystation.asp?inpPointfr=yst')

# XML parsing here
dom = ElementTree.fromstring(response.text)
names = dom.findall('*/Name')
for name in names:
    print(name.text)

我看过其他人推荐zeep解析 soap xml,但我发现很难理解。

最佳答案

这里的问题是处理 XML 命名空间:

import requests
from xml.etree import ElementTree

response = requests.get('http://www.labs.skanetrafiken.se/v2.2/querystation.asp?inpPointfr=yst')

# define namespace mappings to use as shorthand below
namespaces = {
    'soap': 'http://schemas.xmlsoap.org/soap/envelope/',
    'a': 'http://www.etis.fskab.se/v1.0/ETISws',
}
dom = ElementTree.fromstring(response.content)

# reference the namespace mappings here by `<name>:`
names = dom.findall(
    './soap:Body'
    '/a:GetStartEndPointResponse'
    '/a:GetStartEndPointResult'
    '/a:StartPoints'
    '/a:Point'
    '/a:Name',
    namespaces,
)
for name in names:
    print(name.text)

命名空间来自 xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"xmlns="http://www.etis.fskab.se/v1.0/ETISws" Envelope 上的属性和 GetStartEndPointResponse节点分别。

请记住,命名空间由父节点的所有子节点继承,即使命名空间没有在子标签上明确指定为 <namespace:tag> 也是如此。 .

注意:我必须使用 response.content而不是 response.body .

关于python - 如何用 Python 解析 SOAP XML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45250626/

相关文章:

c# - 在 C# 中从分层数据集创建 XML

mysql - 使用 XPath 和编码导入 xml

python - 如何从串行数据中减少 'readline()' 所花费的时间

python - 删除日期时间差异的值,并进行修订

python - 如何识别某个图像何时消失

Python 正则表达式反向引用命名组

xml - XML/XSLT substring-before 能否将多个匹配字符串作为第二个参数?

python - 使用 Pytorch 为神经机器翻译加载巨大的文本文件

python - 从另一个线程调用线程中的方法,python

python - 将 Pandas DataFrame 与 In-Memory Feather 相互转换