Search code examples
pythonxml

How to parse this simple XML?


I'm trying to parse thhis simple XML:

import xml.etree.ElementTree as ET

data = """
<ns2:Request xmlns:ns2="urn://www.example.com">
    <ns2:User>
        <ns2:Name>John</ns2:Name>
        <ns2:Surname>Snow</ns2:Surname>
        <ns2:Email>[email protected]</ns2:Email>
        <ns2:Birthday>2005-10-23T04:00:00+03:00</ns2:Birthday>
    </ns2:User>
</ns2:Request>
"""

namespaces = {"ns2": "urn://www.example.com"}

xml = ET.fromstring(data)

name = xml.find("ns2:Email", namespaces)  # returns None

Name is read as None. The code above does not works as expected. How to parse single Name, Surname, Email and Birthday fields?


Solution

  • You'll need to make sure you navigate through the XML hierarchy and use the correct namespace when searching for the elements

    # You need to search for the User element first and then get the child elements
    user_element = xml.find("ns2:User", namespaces)
    
    name = user_element.find("ns2:Name", namespaces).text
    surname = user_element.find("ns2:Surname", namespaces).text
    email = user_element.find("ns2:Email", namespaces).text
    birthday = user_element.find("ns2:Birthday", namespaces).text
    
    print(f"Name: {name}")
    print(f"Surname: {surname}")
    print(f"Email: {email}")
    print(f"Birthday: {birthday}")
    

    It will output

    Name: John
    Surname: Snow
    Email: [email protected]
    Birthday: 2005-10-23T04:00:00+03:00