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 = '''
<root>
    <person>
        <name>Code Tryout</name>
        <age>30</age>
        <city>New York</city>
    </person>
    <person>
        <name>Python Development</name>
        <age>25</age>
        <city>Sydney</city>
    </person>
</root>
'''

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

ET.parse("filename.xml")

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.