Skip to content
Related Articles

Related Articles

Convert XML to CSV in Python

View Discussion
Improve Article
Save Article
  • Last Updated : 24 Jan, 2021

Prerequisites: Pandas

XML stands for Extensible Markup Language. This format is extremely useful for keeping track of small to medium amounts of data. As the data in XML format is not readable by general users, we need to convert it to some user-friendly format like CSV. CSV is easily readable and can be opened using any editor.

Now, let’s take an example to convert XML data to CSV data using python. We will import ElementTree for parsing data of XML format to CSV format. The xml.etree.ElementTree module implements a simple and efficient API for parsing and creating XML data.


  • Import module
  • Declare rows and columns for the data to arranged in csv file
  • Load xml file
  • Parse xml file
  • Write each row to csv file one by one
  • Save csv file

XML data used : 

Link: sample.xml



# 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('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


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!