Python 3 Script to Convert XML to CSV File Using Pandas and Element Tree Library Full Tutorial For Beginners

You are currently viewing Python 3 Script to Convert XML to CSV File Using Pandas and Element Tree Library Full Tutorial For Beginners

 

Welcome folks today in this blog post we will be converting xml to csv file using pandas and element tree library in python. All the full source code of the application is given below.

 

 

Get Started

 

 

In order to get started we need to install the following libraries by using the pip command

 

pip install pandas

 

After installing all the libraries just make an app.py file and copy paste the following code

 

First of all create an employee.xml file and copy paste the following code

 

employee.xml

 

<?xml version="1.0"?>
<company>
    <employee>
        <name>Alaya</name>
        <phone>3290349906</phone>
        <email>alaya@example.com</email>
        <date>2019-03-02 11:16:07</date>
    </employee>
    <employee>
        <name>Carle</name>
        <phone>9059098968</phone>
        <email>carle@example.com</email>
        <date>2019-06-01 10:06:07</date>
    </employee>
    <employee>
        <name>Amma</name>
        <phone>6750390948</phone>
        <email>amma@example.com</email>
        <date>2019-04-05 16:30:07</date>
    </employee>
</company>

 

 

 

 

And now we can copy paste the following code inside the app.py file

 

 

app.py

 

 

import xml.etree.ElementTree as ET
import pandas as pd  

cols = ["name", "phone", "email", "date"]
rows = []

#Parse XML file
tree = ET.parse('employee.xml')
root = tree.getroot()
for elem in root:
        name = elem.find("name").text
        phone = elem.find("phone").text
        email = elem.find("email").text
        date = elem.find("date").text 
            
        rows.append({"name": name, 
                  "phone": phone,
                  "email": email,
                  "date": date})

df = pd.DataFrame(rows, columns = cols) 
  
# write dataframe to csv
df.to_csv('company.csv')

 

 

After running this python script by using the below command

 

python app.py

 

 

After it will create the company.csv file which is shown below

 

 

 

Leave a Reply