Convert XML to CSV in Python
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 :
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:
Last Updated :
21 Mar, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...