查看此处的文档: https://docs.python.org/3.8/library/xml.etree.elementtree.html,我制定了以下脚本来解析 XML 字符串以获取特定的元素节点:
response = """
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<SOAP-ENV:Body>
<UserLoginResponse xmlns="urn:WsAPIUserIntf-IWsAPIUser">
<return xmlns="http://omniticket.network/ovw7">
<ERROR>
<CODE>200</CODE>
<TYPE>Managed</TYPE>
<TEXT>Success</TEXT>
</ERROR>
<SESSIONID>TestSession</SESSIONID>
<USERCODE>API001</USERCODE>
<APPSERVERVERSION>7.4.9.11</APPSERVERVERSION>
<LANGUAGEID>-1</LANGUAGEID>
<PASSWORDEXPIRATION>2020-12-31</PASSWORDEXPIRATION>
<USERAK>FHFHFHFHFHF</USERAK>
</return>
</UserLoginResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
"""
namespaces = {
'UserLoginResponse': 'urn:WsAPIUserIntf-IWsAPIUser',
}
for UserLoginResponse in xml.etree.ElementTree.fromstring(response).findall('UserLoginResponse:return', namespaces):
print(UserLoginResponse)
然而,解压缩的xml.etree.ElementTree.fromstring(response).findall
数组中没有任何内容。
我做错了什么?
<return>
元素的命名空间是http://omniticket.network/ovw7
。
namespaces = {
'UserLoginResponse': 'urn:WsAPIUserIntf-IWsAPIUser',
'ovw7': 'http://omniticket.network/ovw7',
}
tree.findall('.//ovw7:return', namespaces)
# -> [<Element '{http://omniticket.network/ovw7}return' at 0x02FB82A0>]
XPath 开头的.//
在这里是必需的。
所有包含的元素也都在该命名空间中。您还必须对其中任何一个使用前缀:
tree.find('.//ovw7:return/ovw7:SESSIONID', namespaces)
# -> <Element '{http://omniticket.network/ovw7}SESSIONID' at 0x02FB8510>