目标:
获取<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/