Anand Veeraswamy
Anand Veeraswamy

Reputation: 53

python process xml string with namespaces

I have the following XML with namespaces.

<ns:loginResponse xmlns:ns="http://sumo.fsg.gre.ac.uk">
    <ns:return xmlns:ax21="http://sumo.fsg.gre.ac.uk/xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:type="ax21:Authorisation_LoginResults">
        <ax21:key>key</ax21:key>
        <ax21:lastAccess>1569262077707</ax21:lastAccess>
        <ax21:success>true</ax21:success>
    </ns:return>
</ns:loginResponse>

I need to process this code in python. I have gone through the tutorial on The ElementTree XML API at https://docs.python.org/2/library/xml.etree.elementtree.html but I cannot understand how to access the values in tags ax21:key, ax21:lastaccess, etc.

Some code snippet to access these elements in python will be appreciated.

Upvotes: 1

Views: 82

Answers (1)

deathstroke
deathstroke

Reputation: 81

Try using Beautifulsoup for parsing xml:

from bs4 import BeautifulSoup
with open(r"test.xml","r",encoding='utf8') as f:
    content = f.read()
    soup = BeautifulSoup(content,'html.parser')
    for tag in soup.find_all('ax21:key'):
        print(tag.get_text())

Upvotes: 1

Related Questions