Convert XML to CSV in Python
Last Updated :
11 Apr, 2025
Improve
XML (Extensible Markup Language) is widely used to store and transport structured data. However, for tasks like data analysis or spreadsheet editing, CSV (Comma-Separated Values) is far more user-friendly and easier to work with.
To make XML data easier to process, we often convert it to a CSV file. In this article, we will explore how to convert XML to CSV step-by-step with the help of the built-in xml.etree.ElementTree module and the powerful pandas library.
Approach
- Import necessary libraries.
- Define the desired column headers.
- Parse the XML file.
- Extract the relevant data.
- Store it into a pandas DataFrame.
- Export the DataFrame to a CSV file.
To download the XML data used in the examples, click here.
Example
Python Program to Convert XML to CSV.
# Importing the required libraries
import xml.etree.ElementTree as Xet
import pandas as pd
cols = ["name", "phone", "email", "date", "country"]
rows = []
# Parsing the XML file
xmlparse = Xet.parse(r'psth_to_sample.xml')
root = xmlparse.getroot()
for i in root:
name = i.find("name").text
phone = i.find("phone").text
email = i.find("email").text
date = i.find("date").text
country = i.find("country").text
rows.append({"name": name,
"phone": phone,
"email": email,
"date": date,
"country": country})
df = pd.DataFrame(rows, columns=cols)
# Writing dataframe to csv
df.to_csv('output.csv')
Output:

Code Breakdown:
- We used ElementTree to parse and navigate through the XML structure.
- Data from each record was collected into a list of dictionaries.
- Finally, we used pandas to create a CSV file from that structured data.
To learn about the pandas module in depth, refer to: Python Pandas Tutorial