Skip to content

Q&A · Answered

How to parse XML in Python

asked 9 months, 1 week ago 1256 views 1 answer
13

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

1 Answer

One accepted
30

Accepted answer

Not confirmed since it was written, 9 months, 1 week ago
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"]')

Your answer

Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.

Shown beside your answer and never checked, so it cannot be a name someone already has here.

No account needed to answer. Sign in instead and it carries your name and earns reputation.