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.
Approach
- 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
Program:
Python3
import xml.etree.ElementTree as Xet
import pandas as pd
cols = [ "name" , "phone" , "email" , "date" , "country" ]
rows = []
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)
df.to_csv( 'output.csv' )
|
Output:

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
24 Jan, 2021
Like Article
Save Article