I would recommend pandasread_xml() and to_csv() function, 3-liner:

Compare the documentation: to_csv, read_xml

import pandas as pd

df = pd.read_xml('employee.xml')
df.to_csv('out.csv', index=False)

Output -> (CSV-file):

id,name,age,salary,division
303,varma,20,120000,3
304,Cyril,20,900000,3
305,Yojith,20,900000,3
Answer from Hermann12 on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › convert-xml-to-csv-in-python
Convert XML to CSV in Python - GeeksforGeeks
July 23, 2025 - We used ElementTree to parse and navigate through the XML structure. Data from each record was collected into a list of dictionaries. Finally, we used pandas to create a CSV file from that structured data. To learn about the pandas module in depth, refer to: Python Pandas Tutorial
Top answer
1 of 2
7

I would recommend pandasread_xml() and to_csv() function, 3-liner:

Compare the documentation: to_csv, read_xml

import pandas as pd

df = pd.read_xml('employee.xml')
df.to_csv('out.csv', index=False)

Output -> (CSV-file):

id,name,age,salary,division
303,varma,20,120000,3
304,Cyril,20,900000,3
305,Yojith,20,900000,3
2 of 2
2

I recommend just using libraries because they're usually very optimised. I'll talk about that later. For now, here's a way that utilises the xml.dom.minidom module, which is a part of the Python standard library, so no additional libraries are required.

Edit: rewrote the last part using the standard CSV library instead of manually writing the file, as suggested by a comment. That makes for 2 Python built-in modules, not 1. The original code for the CSV writing will be at the end of the reply, if you're interested.

from xml.dom import minidom
from csv import DictWriter

# Step 1: Read and parse the XML file
# Write it as a string, or open the file and read it
xml_file = open('employees.xml', 'r')
xml_data = xml_file.read()

dom = minidom.parseString(xml_data)
employees = dom.getElementsByTagName('employee')

xml_file.close()

# Step 2: Extract the required information
data = []
for employee in employees:
    emp_data = {}
    for child in employee.childNodes:
        if child.nodeType == minidom.Node.ELEMENT_NODE:
            emp_data[child.tagName] = child.firstChild.data
    data.append(emp_data)

# Step 3: Write the extracted information to a CSV file
with open('output.csv', 'w', newline = '') as csv_file:
    fieldnames = ['id', 'name', 'age', 'salary', 'division']
    writer = DictWriter(csv_file, fieldnames = fieldnames)

    writer.writeheader()
    for emp_data in data:
        writer.writerow(emp_data)


Don't reinvent the wheel, just realign it.

— Anthony J. D'Angelo, I think

I recommend NOT using this code. You should really just use lxml. It's extremely simple and easy to use and can handle complex XML structures with nested elements and attributes. Let me know how everything goes!


Original CSV write code without CSV library
# Step 3: Write the extracted information to a CSV file
with open('output.csv', 'w') as f:
    f.write('id,name,age,salary,division\n')
    for emp_data in data:
        f.write(f"{emp_data['id']},{emp_data['name']},{emp_data['age']},{emp_data['salary']},{emp_data['division']}\n")
Discussions

pandas - XML to CSV Python - Stack Overflow
The XML data(file.xml) for the state will look like below More on stackoverflow.com
🌐 stackoverflow.com
April 11, 2025
Simple CSV to XML Conversion - Python - Stack Overflow
I am looking for a way to automate the conversion of CSV to XML. Here is an example of a CSV file, containing a list of movies: Here is the file in XML format: More on stackoverflow.com
🌐 stackoverflow.com
Converting CSV file to XML
Excel can export data in an XML format. Open it in Excel and simply export it, no programming needed. I believe you do need to enable developer mode. More on reddit.com
🌐 r/CodingHelp
6
1
September 8, 2024
Read xml column inside csv file with Python
Hi, I am very new in Python and need to read an xml column inside a csv file with Python. I can see some code on google on how to read that csv file but I don’t know how to read the xml column inside the csv file. Can someone help? any idea would be appreciated. Thank you! More on discuss.python.org
🌐 discuss.python.org
0
0
July 22, 2022
🌐
Python.org
discuss.python.org › python help
Convert xml to excel/csv - Python Help - Discussions on Python.org
October 15, 2022 - Please help me in converting XML file into excel/csv. Thank you in advance.
🌐
GitHub
github.com › waheed0332 › xml2csv
GitHub - waheed0332/xml2csv: Python scripts for processing XML documents and converting to CSV. Also works on nested xml files. · GitHub
Converts XML files into csv file, this script is capable of converting extremely nested xml files. This script utilize power of multiprocessing to convert huge data in less time. Install required libraries using following command before running script. pip install -r requirements.txt · python xml2csv.py -f ./xml-samples/1.xml -csv out.csv
Starred by 23 users
Forked by 7 users
Languages   Python
🌐
Medium
medium.com › @ayushnandanwar003 › simplifying-data-conversion-a-comprehensive-guide-to-converting-xml-to-csv-in-python-b22c24b02628
Simplifying Data Conversion: A Comprehensive Guide to Converting XML to CSV in Python | by Ayush Nandanwar | Medium
April 26, 2024 - To convert XML data to CSV format in Python, we’ll leverage the power of two core modules: xml.etree.ElementTree for parsing XML and csv for handling CSV files.
🌐
Medium
medium.com › @meiyee715 › converting-xml-to-csv-python-xml-etree-25fec8e72626
Converting XML to CSV: Python xml.etree | by Amy Leong | Medium
October 14, 2023 - Replace path_to_your_xml_file.xml and path_to_output.csv with your desired paths. The provided script is a basic example, and real-world XML files can vary widely in their structure. Depending on the nature of the XML, you may need to account for attributes, nested elements, and other complexities. The beauty of Python is that it offers the flexibility to handle these scenarios with a bit more logic.
🌐
Saturn Cloud
saturncloud.io › blog › converting-complex-xml-files-to-pandas-dataframecsv-in-python
Converting Complex XML Files to Pandas DataFrame/CSV in Python | Saturn Cloud Blog
December 28, 2023 - The first step in converting an XML file to a DataFrame or CSV is parsing the XML file. We’ll use the xml.etree.ElementTree module in Python, which provides a lightweight and efficient API for parsing and creating XML data.
Find elsewhere
🌐
SysTools Group
systoolsgroup.com › home › how to convert xml to csv file? 5 easy methods
Convert XML to CSV Format in Bulk Using the Best Five Methods
October 8, 2025 - Select the Language and then “XML” to apply formatting. Now select the “File” tab and choose the “Save As” button. Choose “CSV” as the saving type. Finally, all your XML data is saved in CSV format.
🌐
Medium
medium.com › analytics-vidhya › converting-xml-data-to-csv-format-using-python-3ea09fa18d38
Converting XML data to CSV format using Python | by Pralhad Teggi | Analytics Vidhya | Medium
November 20, 2019 - The xml dump has huge number of events and for every event, I would like to extract an important attributes like title of the event, description, state, solution, severity, time of the event creation etc. This is achieved by the below code snippet. ... The code checks whether the extracted field is None and the extracted data is appended to a list. Once the extraction is completed, the list is written to the csv file as below.
🌐
Plain English
python.plainenglish.io › converting-xml-to-csv-using-python-d723a3df3de1
Convert XML to CSV Using Python. A guide on converting XML to CSV using… | by Mansoor Basha Syed | Python in Plain English
July 7, 2022 - #3 # Selecting headers for CSV HEADERS = [‘name’, ‘role’ ,’age’]rows = []# Interating through each element to get row data for employee in employee_data_list: name = employee["name"] role= employee["role"] age = employee["age"] # Adding data of each employee to row list rows.append([name,role,age])#Writing to CSV with open('employee_data.csv', 'w',newline="") as f: write = csv.writer(f) write.writerow(HEADERS) write.writerows(rows) The data can also be parsed by using ordered dict but for a better understanding of data, I have converted the data to a dictionary in the code snippet #3. ... More content at plainenglish.io. Sign up for our free weekly newsletter. Get exclusive access to writing opportunities and advice in our community Discord. ... New Python content every day.
🌐
Plain English
plainenglish.io › home › blog › python › convert xml to csv using python
Convert XML to CSV Using Python
February 17, 2022 - #2 # Reading xml file with open("sample.xml", 'r') as file: filedata = file.read() # Converting xml to python dictionary (ordered dict) data_dict = xmltodict.parse(filedata)
🌐
Teleport
goteleport.com › resources › tools › xml-to-csv-converter
XML to CSV Converter | Instantly Transform XML to CSV | Teleport
Convert XML data to CSV instantly with our free online tool. Simplify your data conversions with fast, accurate processing.
🌐
Like Geeks
likegeeks.com › home › python › pandas › export xml to csv using python pandas
Export XML to CSV using Python Pandas
December 16, 2023 - You can use the xml.etree.ElementTree module to parse the XML file. It iterates over each node, extracts the relevant data, and stores it in a dictionary. Finally, the dictionary is converted into a DataFrame and exported to a CSV file.
🌐
Wondershare PDF
pdf.wondershare.com › home › pdf converter › how to convert xml to csv in 5 easy ways
How to Convert XML to CSV in 5 Easy Ways
January 6, 2026 - You can convert XML to CSV using ElementTree module of the in-built xml module in Python. It can parse an XML document as a parameter and save the file in the form of tree, which has a getroot() method that returns the root element of the tree.
Top answer
1 of 5
23

A possible solution is to first load the csv into Pandas and then convert it row by row into XML, as so:

import pandas as pd
df = pd.read_csv('untitled.txt', sep='|')

With the sample data (assuming separator and so on) loaded as:

          Title                   Type Format  Year Rating  Stars  \
0  Enemy Behind           War,Thriller    DVD  2003     PG     10   
1  Transformers  Anime,Science Fiction    DVD  1989      R      9   

             Description  
0          Talk about...  
1  A Schientific fiction  

And then converting to xml with a custom function:

def convert_row(row):
    return """<movietitle="%s">
    <type>%s</type>
    <format>%s</format>
    <year>%s</year>
    <rating>%s</rating>
    <stars>%s</stars>
    <description>%s</description>
</movie>""" % (
    row.Title, row.Type, row.Format, row.Year, row.Rating, row.Stars, row.Description)

print '\n'.join(df.apply(convert_row, axis=1))

This way you get a string containing the xml:

<movietitle="Enemy Behind">
    <type>War,Thriller</type>
    <format>DVD</format>
    <year>2003</year>
    <rating>PG</rating>
    <stars>10</stars>
    <description>Talk about...</description>
</movie>
<movietitle="Transformers">
    <type>Anime,Science Fiction</type>
    <format>DVD</format>
    <year>1989</year>
    <rating>R</rating>
    <stars>9</stars>
    <description>A Schientific fiction</description>
</movie>

that you can dump in to a file or whatever.

Inspired by this great answer.


Edit: Using the loading method you posted (or a version that actually loads the data to a variable):

import csv              
f = open('movies2.csv')
csv_f = csv.reader(f)   
data = []

for row in csv_f: 
   data.append(row)
f.close()

print data[1:]

We get:

[['Enemy Behind', 'War', 'Thriller', 'DVD', '2003', 'PG', '10', 'Talk about...'], ['Transformers', 'Anime', 'Science Fiction', 'DVD', '1989', 'R', '9', 'A Schientific fiction']]

And we can convert to XML with minor modifications:

def convert_row(row):
    return """<movietitle="%s">
    <type>%s</type>
    <format>%s</format>
    <year>%s</year>
    <rating>%s</rating>
    <stars>%s</stars>
    <description>%s</description>
</movie>""" % (row[0], row[1], row[2], row[3], row[4], row[5], row[6])

print '\n'.join([convert_row(row) for row in data[1:]])

Getting identical results:

<movietitle="Enemy Behind">
    <type>War</type>
    <format>Thriller</format>
    <year>DVD</year>
    <rating>2003</rating>
    <stars>PG</stars>
    <description>10</description>
</movie>
<movietitle="Transformers">
    <type>Anime</type>
    <format>Science Fiction</format>
    <year>DVD</year>
    <rating>1989</rating>
    <stars>R</stars>
    <description>9</description>
</movie>
2 of 5
3

I tried to generalize robertoia's function convert_row for any header instead of writing it by hand.

import csv  
import pandas as pd
            
f = open('movies2.csv')
csv_f = csv.reader(f)   
data = []

for row in csv_f: 
   data.append(row)
f.close()

df = pd.read_csv('movies2.csv')
header= list(df.columns)

def convert_row(row):
     str_row = """<%s>%s</%s> \n"""*(len(header)-1)
     str_row = """<%s>%s""" +"\n"+ str_row + """</%s>"""
     var_values = [list_of_elments[k] for k in range(1,len(header)) for list_of_elments in [header,row,header]]
     var_values = [header[0],row[0]]+var_values+[header[0]]
     var_values =tuple(var_values)
     return str_row % var_values

text ="""<collection shelf="New Arrivals">"""+"\n"+'\n'.join([convert_row(row) for row in data[1:]])+"\n" +"</collection >"
print(text)
with open('output.xml', 'w') as myfile: 
  myfile.write(text)

Of course with pandas now, it is simpler to just use to_xml() :

df= pd.read_csv('movies2.csv')
with open('outputf.xml', 'w') as myfile: 
  myfile.write(df.to_xml())

🌐
Sonra
sonra.io › home › xml › xml conversion using python in 2025
XML Conversion Using Python in 2026 - Sonra
January 14, 2025 - Output consists of multiple csv files where each csv file contains each tag and its corresponding details. ... xmltodict is a Python library that makes working with XML feel like working with JSON by converting XML into Python dictionaries.
🌐
Reddit
reddit.com › r/codinghelp › converting csv file to xml
r/CodingHelp on Reddit: Converting CSV file to XML
September 8, 2024 -

I don't know if this is the right place to post this, but I'm looking for someone who can create a process to convert a daily csv file to xml that can be imported into our billing software.

I'm just looking for a way to find someone to pay to get this set up for me (the company I work for). I've tried searching and have come up empty, so am reaching out to reddit where I get all of my questions answered!

To sum up, I'm looking for where I would search to find someone to write a program / process for me to use to convert a csv file into xml to be able to be imported into a billing software program.

Thanks!

🌐
GroupDocs Cloud
blog.groupdocs.cloud › groupdocs cloud blog › convert xml to csv and csv to xml in python
Convert XML to CSV and CSV to XML in Python
November 1, 2022 - For converting XML to CSV online, or vice versa, I will be using Python SDK of GroupDocs.Conversion Cloud API. This Python document conversion library is a platform-independent open-source library and file format conversion service. It is 100% free, secure and easy to use Python library for converting file formats.
🌐
Python.org
discuss.python.org › python help
Read xml column inside csv file with Python - Python Help - Discussions on Python.org
July 22, 2022 - Hi, I am very new in Python and need to read an xml column inside a csv file with Python. I can see some code on google on how to read that csv file but I don’t know how to read the xml column inside the csv file. Can …