Python:XML元素树findall()不返回任何内容

时间:2019-12-03 12:15:01

标签: python xml elementtree python-3.8

请看这里的文档: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数组中什么也没有。

我在做什么错了?

1 个答案:

答案 0 :(得分:2)

<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>