Micheal J. Roberts
Micheal J. Roberts

Reputation: 4180

Python: XML Element Tree findall() not returning anything

Looking at the documentation here: https://docs.python.org/3.8/library/xml.etree.elementtree.html, I have formulated the following script to parse from an XML string to obtain a particular element node:

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)

Yet, there is nothing in the unpacked xml.etree.ElementTree.fromstring(response).findall array.

What am I doing wrong?

Upvotes: 0

Views: 1151

Answers (1)

Tomalak
Tomalak

Reputation: 338406

The namespace for the <return> element is 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>]

The .// at the start of the XPath is necessary here.

All contained elements are also in that namespace. You would have to use the prefix for any of them as well:

tree.find('.//ovw7:return/ovw7:SESSIONID', namespaces)

# -> <Element '{http://omniticket.network/ovw7}SESSIONID' at 0x02FB8510>

Upvotes: 2

Related Questions