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
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")
🌐
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.
Discussions

Is there a simple way to convert xml format to csv using python? - Stack Overflow
I have the below xml that i would want to convert to csv ( delimiter like '|' or octal ) using python. I tried converting the xml into dict and then to csv . I am looking if there are any easy or More on stackoverflow.com
🌐 stackoverflow.com
How do I convert XML into a CSV in the most efficient way possible?
How To Parse and Convert XML to CSV using Python . More on reddit.com
🌐 r/datascience
7
3
July 5, 2017
Convert XML to (meaningful) CSV
There's a lot of ways. These two would probably be the easiest, assuming the data format stays the same. XSL: https://askubuntu.com/questions/174143/convert-xml-to-csv-shell-command-line Database: Import data into the db then export back out in chosen format. https://stackoverflow.com/questions/19007884/import-xml-files-to-postgresql https://stackoverflow.com/questions/47812771/exporting-postgres-database-data-to-xml CSV is trivial with postgresql https://gist.github.com/nepsilon/f2937fe10fe8b0efc0cc More on reddit.com
🌐 r/sysadmin
12
4
December 5, 2019
Convert huge XML(Size around 500mb) to CSV using Python

May I suggest you edit your post to provide a link to the XML, and show us, in post (code blocks) the code you've tried.

More on reddit.com
🌐 r/learnpython
3
0
October 24, 2016
🌐
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.
🌐
GeeksforGeeks
geeksforgeeks.org › python › convert-xml-to-csv-in-python
Convert XML to CSV in Python - GeeksforGeeks
July 23, 2025 - In this article, we will explore how to convert XML to CSV step-by-step with the help of the built-in xml.etree.ElementTree module and the powerful pandas library. Import necessary libraries. Define the desired column headers. Parse the XML file.
Top answer
1 of 1
1

I'd do this in a very explicit way rather than trying to hack xmltodict to fit your needs.

The only downside I see with this approach is a bit of repetition with the hardcoded headers and tags names.

Also, I don't know how regular you input XML is going to be. If it's possible that some of the tags will not be present then you will need to add some error handling (because node.find will return None, then .text will cause an AttributeError).

rows = []
for abc_node in tree.findall('abc'):
    rate_node = abc_node.find('Rate')
    fee_node = abc_node.find('fee')
    row = {'id': abc_node.find('id').text,
           'uniqueid': abc_node.find('uniqueid').text,
           'Name': abc_node.find('Name').text,
           'rate_mrp': rate_node.find('mrp').text,
           'rate_discount': rate_node.find('discount').text,
           'rate_discountmonths': rate_node.find('discountmonths').text,
           'fee_type': fee_node.find('type').text,
           'fee_minimumfee': fee_node.find('minimumfee').text,
           'fee_maxfee': fee_node.find('maxfee').text}
    rows.append(row)

with open('test.csv', 'w', encoding='utf8') as f:
    headers = ['id', 'uniqueid', 'Name', 'rate_mrp', 'rate_discount', 'rate_discountmonths',
               'fee_type', 'fee_minimumfee', 'fee_maxfee']
    dict_writer = csv.DictWriter(f, fieldnames=headers, lineterminator='\n')
    dict_writer.writeheader()
    dict_writer.writerows(rows)

Output

id,uniqueid,Name,rate_mrp,rate_discount,rate_discountmonths,fee_type,fee_minimumfee,fee_maxfee
23,23_0,,6.40000,10.00%,2,off,"£1,500.75",£10K
35,35_0,,7.90000,5.00%,5,offer,£1k,"£22,000" 

If you want | as delimiter just add delimiter='|' to csv.DictWriter(f, fieldnames=headers, lineterminator='\n')

then the output is

id|uniqueid|Name|rate_mrp|rate_discount|rate_discountmonths|fee_type|fee_minimumfee|fee_maxfee
23|23_0||6.40000|10.00%|2|off|£1,500.75|£10K
35|35_0||7.90000|5.00%|5|offer|£1k|£22,000
🌐
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.
Find elsewhere
🌐
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
🌐
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 - To understand how it works with XML.etree. Only for the ElementTree module, follow these steps — · Step 1. First, all you have to do is open up Python and paste the following code into it. ... Step 2. After pasting the code, select the “Run” option from the top bar. In this way, you will save the CSV file in the same folder as this script. You will get multiple online converters to convert XML to CSV format.
🌐
Sonra
sonra.io › home › xml › convert xml to csv like a pro – essential tools & methods
Convert XML to CSV Like a Pro – Essential Tools & Methods
March 22, 2025 - You can refer to our guide XML conversion in Python where we compare the various options and libraries such as Element Tree and lxml of converting XML to CSV.
🌐
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.
🌐
Reddit
reddit.com › r/datascience › how do i convert xml into a csv in the most efficient way possible?
r/datascience on Reddit: How do I convert XML into a CSV in the most efficient way possible?
July 5, 2017 -

Currently, I'm receiving a large amount of data from different devices, an issue I'm having is that the data is in different formats. Ideally, I would like them to be CSV but I need to do this without a heavy overhead.

So far I've been looking into parse generators and I've seen data pipelining come up a few times.

Help a geek out

🌐
AskPython
askpython.com › home › converting data in csv to xml in python
Converting Data in CSV to XML in Python - AskPython
April 4, 2023 - XML also provides styling options, to beautifully display the data. An XML file can be opened with supported browsers and can be edited with text editors or dedicated XML editors. The main motto of this article is to write a program that reads data from the CSV file and converts it into structured XML format.
🌐
Quora
quora.com › How-do-you-convert-XML-to-CSV-in-Python
How to convert XML to CSV in Python - Quora
Answer (1 of 4): In a strict sense? You don’t. CSV is a format (if it can even be called that!) for encoding row-based data. XML is a format for encoding tree-based data. One expects all entries to follow a simple, “all of these entries have the same fields, and a value in those fields”, ...
🌐
JSON Formatter
jsonformatter.org › xml-to-csv
Best XML to CSV Converter Online
XML to CSV is very unique tool for convert JOSN to CSV and allows to download, save, share and print XML to CSV data..
🌐
Aspose
products.aspose.com › aspose.cells › python via .net › conversion › xml to csv
Python XML to CSV - XML to CSV Converter | products.aspose.com
November 13, 2025 - Add a library reference (import the library) to your Python project. Load XML file with an instance of Workbook. Convert XML to CSV by calling Workbook.save method.
🌐
ConvertCSV
convertcsv.com › xml-to-csv.htm
XML To CSV Converter
This conversion is now available as an API at ConvertCsv.io · You can also force double quotes around each field value or it will be determined for you. The output CSV header row is optional. Your XML input should be record oriented in order to get good results.
🌐
e-iceblue
e-iceblue.com › Tutorials › Python › Spire.XLS-for-Python › Program-Guide › Conversion › convert-xml-to-csv-in-python.html
How to Convert XML to CSV in Python: A Complete Guide
A robust converter must be able to handle these differences and map hierarchical XML into a flat, tabular CSV format. To load and parse an XML file in Python, you can use the built-in xml.etree.ElementTree library. This library lets you navigate the XML tree, retrieve elements, and access attributes.
🌐
Plus2Net
plus2net.com › python › xml-to-csv.php
Convert XML to CSV in Python
root.findall('record'): Finds all the <record> elements in the XML file. csv.DictWriter: Writes the data into a CSV file with headers and rows. --- ... You need a quick and straightforward way to convert XML to CSV.
🌐
Aryson Technologies
arysontechnologies.com › home › convert xml to csv: easy methods explored
Convert XML to CSV: Easy Methods Explored
February 9, 2026 - Your XML data will now be displayed as a structured table in Excel. Finally, go to File >> Save As, select CSV as the format, and save the file. If you’re comfortable with coding, using Python is a flexible way to convert XML data to CSV format.