How to parse XML in Python

Answered
Jan 05, 2026 795 views 1 answers
13

I need to read and parse XML files in Python. What is the best approach?

L
Asked by layla_web
Bronze 276 rep

1 Answer

30
import xml.etree.ElementTree as ET

# Parse XML file
tree = ET.parse('data.xml')
root = tree.getroot()

# Parse XML string
root = ET.fromstring(xml_string)

# Find elements
for child in root:
    print(child.tag, child.attrib)

# Find specific elements
for item in root.findall('.//item'):
    name = item.find('name').text
    print(name)

# Using XPath
elements = root.findall('.//item[@type="book"]')
F
Answered by fatima_dev 1 week, 2 days ago
Silver 169 rep

Your Answer

You need to be logged in to answer questions.

Log In to Answer

Related Questions

Hot Questions

No hot questions available.