Open In App

Convert XML to CSV in Python

Improve
Improve
Like Article
Like
Save
Share
Report

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




# 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
df.to_csv('output.csv')


Output:


Last Updated : 21 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads