create a csv file which is Excel friendly format.

import xml.etree.ElementTree as ET
from os import listdir


xml_lst = [f for f in listdir() if f.startswith('xml')]
fields = ['RecordID','I_25Hz_1s','I_75Hz_2s'] # TODO - add rest of the fields
with open('out.csv','w') as f:
  f.write(','.join(fields) + '\n')
  for xml in xml_lst:
    root = ET.parse(xml)
    values = [root.find(f'.//{f}').text for f in fields]
    f.write(','.join(values) + '\n')

output

RecordID,I_25Hz_1s,I_75Hz_2s
Madird01,56.40,0.36
London01,56.40,0.36
Answer from balderman on Stack Overflow
🌐
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.
Top answer
1 of 3
2

create a csv file which is Excel friendly format.

import xml.etree.ElementTree as ET
from os import listdir


xml_lst = [f for f in listdir() if f.startswith('xml')]
fields = ['RecordID','I_25Hz_1s','I_75Hz_2s'] # TODO - add rest of the fields
with open('out.csv','w') as f:
  f.write(','.join(fields) + '\n')
  for xml in xml_lst:
    root = ET.parse(xml)
    values = [root.find(f'.//{f}').text for f in fields]
    f.write(','.join(values) + '\n')

output

RecordID,I_25Hz_1s,I_75Hz_2s
Madird01,56.40,0.36
London01,56.40,0.36
2 of 3
1

When you need to iterate over files in folder with similar names one of the ways could be make a pattern and use glob. To make sure that returned path is file you can use isfile().

Regarding XML, I see that basically you need to write values of every terminal tag in column with name of this tag. As you have various files you can create tag-value dictionaries from each file and store them into ChainMap. After all files processed you can use DictWriter to write all data into final csv file.

This method is much more safe and flexible then use static column names. Firstly program will collect all possible tag(column) names from all files, so in case if XML doesn't have such a tag or have some extra tags it won't throw an exception and all data will be saved.

Code:

import xml.etree.ElementTree as ET
from glob import iglob
from os.path import isfile, join
from csv import DictWriter
from collections import ChainMap

xml_root = r"C:\data\Desktop\Blue\XML-files"
pattern = "xmlfile_*"
data = ChainMap()
for filename in iglob(join(xml_root, pattern)):
    if isfile(filename):
        tree = ET.parse(filename)
        root = tree.getroot()
        temp = {node.tag: node.text for node in root.iter() if not node}
        data = data.new_child(temp)

with open(join(xml_root, "data.csv"), "w", newline="") as f:
    writer = DictWriter(f, data)
    writer.writeheader()
    writer.writerows(data.maps[:-1])  # last is empty dict

Upd. If you want to use xlsx format instead of csv you have to use third-party library (e.g. openpyxl). Example of usage:

from openpyxl import Workbook

...

wb = Workbook(write_only=True)
ws = wb.create_sheet()
ws.append(list(data))  # write header
for row in data.maps[:-1]:
    ws.append([row.get(key, "") for key in data])
wb.save(join(xml_root, "data.xlsx"))
Discussions

How to parse XML into an excel sheet?
Depending on the complexity of the xml, the easiest way might be to simply read into a pandas dataframe and write it back out as Excel. https://pandas.pydata.org/docs/reference/api/pandas.read_xml.html# https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_excel.html More on reddit.com
🌐 r/learnpython
2
3
January 12, 2022
Python extract data from xml and save it to excel - Stack Overflow
I would like to extract some data from an XML file and save it in a table format, such as XLS or DBF. Here is XML file i have: More on stackoverflow.com
🌐 stackoverflow.com
May 22, 2017
How can I convert XML to CSV in Python without using libraries such as Etree or Xmltodict? - Stack Overflow
xml file would be like this: 303 varma 20 120000 ... More on stackoverflow.com
🌐 stackoverflow.com
Converting multisheet XML to Excel with python - Stack Overflow
I have hundreds of XML files I need to convert to XLSX for downstream analysis, but I have far too many to do by hand. I have been trying to figure out a python way to do this, and have found a num... More on stackoverflow.com
🌐 stackoverflow.com
🌐
PyPI
pypi.org › project › xml2xlsx
xml2xlsx · PyPI
This project is intended to create xlsx files from xml api to openpyxl, supposedly generated by other tamplate engines (i.e. django, jinja). This is a merely an xml parser translating mostly linearly to worksheet, rows and finally cells of the Excel workbook.
      » pip install xml2xlsx
    
Published   Sep 16, 2024
Version   1.0.2
🌐
Aspose
blog.aspose.com › aspose.blogs › convert xml to excel in python
Convert XML to Excel Python | Export XML to Excel in Python
March 15, 2024 - Convert XML to Excel in Python. Export data from an XML file to Excel programmatically in Python using Aspose.Cells for Python API.
🌐
Like Geeks
likegeeks.com › home › python › pandas › export xml to excel using python pandas
Export XML to Excel using Python Pandas
April 27, 2025 - You can export XML files to Excel by reading the XML using Pandas read_xml() and then exporting the result DataFrame to Excel using Pandas to_excel(). ... <Customers> <Customer> <ID>1</ID> <Name>Customer A</Name> <Contact>1234567890</Contact> ...
🌐
GitHub
github.com › vrushabhkaushik › XML-to-Excel-Conversion
GitHub - vrushabhkaushik/XML-to-Excel-Conversion: The python script reads the XML file name from user's input, and then using data frame, it writes the data to an Excel sheet
The python script reads the XML file name from user's input, and then using data frame, it writes the data to an Excel sheet - vrushabhkaushik/XML-to-Excel-Conversion
Starred by 5 users
Forked by 2 users
Languages   Python 100.0% | Python 100.0%
🌐
GroupDocs Cloud
blog.groupdocs.cloud › groupdocs cloud blog › convert xml to excel and excel to xml in python
Convert XML to Excel and Excel to XML in Python
October 28, 2022 - Next, convert XML file to Excel workbook in Python programmatically by following the steps given below: ... The code example given below shows how Python convert XML to XLSX without opening file using REST API:
Find elsewhere
🌐
Sonra
sonra.io › home › xml › xml to excel – complete guide to convert & import files
XML to Excel - Complete Guide to Convert & Import Files - Sonra
June 19, 2025 - A breakdown of Excel’s three native XML import methods: what works, what doesn’t. The hidden traps of Power Query, XML Maps, and File → Open. Programmatic options (Python, XSLT) and why they’re often not worth the effort. A smarter, no-code way to convert XML (and XSD!) into clean, structured Excel, automatically.
🌐
Reddit
reddit.com › r/learnpython › how to parse xml into an excel sheet?
r/learnpython on Reddit: How to parse XML into an excel sheet?
January 12, 2022 -

Bare with me, as I'm a novice with python, but basically, I am trying to take an XML file, and plop it into an existing excel workbook in a specific sheet. I know I have done this successfully before, but cannot find the file where I did, nor can I remember how I did.

When I do it manually, the process is pretty straight forward - download the XML file, open it with excel, copy and paste as text into the sheet. Just hoping someone could help me get started here. Thanks so much for your time.

To be more specific this is the layout of the XML file:

<products>

<product active="1" on_sale="0" discountable="1">

<sku>GG1234</sku>

<name><![CDATA[ Product Name Here ]]></name>

<description><![CDATA[Product Description Here ]]></description>

<keywords></keywords>

<price>8.9</price>

<stock_quantity>220</stock_quantity>

<reorder_quantity>0</reorder_quantity>

<height>4.25</height>

<length>1.25</length>

<diameter>2.5</diameter>

<weight>0.53</weight>

<color></color>

<material>Material Here/material>

<barcode>0000000000</barcode>

<release_date>2010-02-19</release_date>

<images>

<image>/path/path.jpg</image>

<image>/path/path.jpg</image>

<image>/path/path.jpg</image>

<image>/path/path.jpg</image>

</images>

<categories>

<category code="518" video="0" parent="0">Category 1</category>

<category code="525" video="0" parent="528">Category 2</category>

<category code="138" video="0" parent="0">Category 3</category>

<category code="552" video="0" parent="528">Category 4</category>

</categories>

<manufacturer code="AC" video="0">Manufact</manufacturer>

<type code="CL" video="0">Product Type</type>

</product> . . . . .

<products>

What I need is for the follow values to populate the top row as the header of the excel file:

active
on_sale
disctountable
sku
name
description
keywords
price
stock_quantity
reorder_quantity
height
length
diameter
weight
color
material
barcode
release_date
image
category
manufacturer
code2
video3
type
code4
video5

And then their respective values to populate the cells going downward in the columns.

Hope that makes sense

🌐
Aspose
products.aspose.com › aspose.cells › python via .net › conversion › xml to excel
Convert XML to EXCEL in Python Excel Library - Conversion
November 13, 2025 - With Aspose.Cells for Python via NET library, you can easily convert XML to EXCEL programmatically with a few lines of code. Aspose.Cells for Python via NET is capable of building cross-platform applications with the ability to generate, modify, ...
🌐
EasyXLS
easyxls.com › manual › tutorials › python › convert-xml-spreadsheet-to-excel.html
How to convert XML spreadsheet file to Excel in Python
Code sample Python: Convert XML Spreadsheet to Excel file in Python by EasyXLS library. XLSX, XLSM, XLSB, XLS in Python
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")
🌐
Quora
quora.com › How-can-I-convert-XML-to-Excel-using-Python-scripting
How to convert XML to Excel using Python scripting - Quora
Answer: Hi you can use regular expression to extract data. And then you can write the got results into the excel through the python script itself. Re module is used for extracting data and excel module to open and write into the excel file
🌐
SysTools Group
systoolsgroup.com › home › how to convert xml to xlsx format? free & best ways
Convert XML to XLSX / XLS Format using Free and Manual Ways
1 month ago - This write-up provided the best ways to convert XML to XLSX / XLS without opening file. You can easily import XML to Excel formats using the built-in direct option and the Power Query option. If you are a technical person, then you should go ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › convert-xml-to-csv-in-python
Convert XML to CSV in Python - GeeksforGeeks
July 23, 2025 - Export the DataFrame to a CSV file. To download the XML data used in the examples, click here. Python Program to Convert XML to CSV.
🌐
Aspose
kb.aspose.com › cells › python › how-to-convert-xml-to-csv-using-python
How to Convert XML to CSV using Python
July 19, 2023 - It covers the system configuration, step-by-step process, and a runnable code snippet to convert XML to CSV using Python. Moreover, you do not need to install MS Excel or other applications to work with this feature on your end. Prepare the IDE to work with Aspose.Cells for Python via Java to convert XML files to CSV
🌐
freeCodeCamp
forum.freecodecamp.org › python
Convert Excel XML to .xlsx with python - Python - The freeCodeCamp Forum
September 29, 2020 - Hello guys, so i have this XML file which i can open pretty easily using Excel this is the file, but i want to convert it to xlsx or any compatible format to be able to use openpyxl module to it so that i can read it eas…