13
I need to read and parse XML files in Python. What is the best approach?
Loading...
Q&A · Answered
I need to read and parse XML files in Python. What is the best approach?
Accepted answer
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"]')Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.