How to parse XML in Python

In Python, you can use the built-in XML module to parse XML. Here is an example code snippet

import xml.etree.ElementTree as ET

# Sample XML data
xml_data = '''
        <name>Code Tryout</name>
        <city>New York</city>
        <name>Python Development</name>

# Parse the XML data
root = ET.fromstring(xml_data)

# Iterate through each 'person' element
for person in root.findall('person'):
    # Extract data from each 'person' element
    name = person.find('name').text
    age = person.find('age').text
    city = person.find('city').text

    # Print the extracted data
    print(f"Name: {name}, Age: {age}, City: {city}")

This example assumes a simple XML structure with a root element () containing multiple elements, each with , and child elements.

Make sure to replace the xml_data variable with your actual XML data. If your XML is in a file, you can use ET.parse(“filename.xml”) instead of ET.fromstring(xml_data) to parse the XML from a file.


This example demonstrates a basic XML parsing process using Python’s built-in XML module. Depending on your specific XML structure, you may need to adapt the code to fit your needs.