Use the code provided by Nk03 to convert the XML you're loading to a python dictionary.

import xmltodict

d = xmltodict.parse("""
<D1>
    <RECORD>
            <ELEC>EL-13</ELEC>
            <VAL>10</VAL>
            <POWER>Max</POWER>
            <WIRING>2.3</WIRING>
            <ENABLED>Yes</ENABLED>
    </RECORD>       
    <RECORD>
            <ELEC>EL-14</ELEC>
            <VAL>30</VAL>
            <POWER>Max</POWER>
            <WIRING>1.1</WIRING>
            <ENABLED>Yes</ENABLED>
    </RECORD>       
</D1>
""")

From there, you can generate a list of keys to use as the column names for the DataFrame:

for key in parsed_dictionary.keys():
    cols.append(key)
Answer from Jordan Renaud on Stack Overflow
🌐
Delft Stack
delftstack.com › home › howto › python › xml to csv python
How to Convert XML to CSV Using Python | Delft Stack
February 2, 2024 - This part is crucial as it ensures the code’s flexibility to handle any XML structure. The headers for the CSV file are dynamically extracted from the XML file. The find() method, combined with an XPath expression, is used to locate the first ...
Discussions

python - How to deal with dynamic columns while converting xml to csv - Stack Overflow
I want to parse through Xml file and convert it to Csv , The columns are dynamic between those Dab tags(As we can see there is an tag in second section not in the first one though. I want to get id attribs and text for the one which has no id. I tried but not able to figure it our as I'm newbie don't know how to deal with dynamic columns. using python ... More on stackoverflow.com
🌐 stackoverflow.com
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
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
Convert xml to excel/csv
Please help me in converting XML file into excel/csv. Thank you in advance. More on discuss.python.org
🌐 discuss.python.org
0
0
October 15, 2022
🌐
Stack Overflow
stackoverflow.com › questions › 67380070 › parsing-xml-file-to-csv-with-dynamic-xml-structure
python - parsing xml file to csv with dynamic xml structure - Stack Overflow
#first collect your data: data = [] rows = root.findall('.//rows') for row in rows: items = [row.attrib['id'], row.find('./column[@name="Organization"]'), row.find('./column[@name="Location"]'), row.find('./column[@name="Candidate.Address"]/Address1[@name="Candidate.ResidentialAddress"]'), row.find('./column[@name="Candidate.Address"]/Address1[@name="Candidate.OfficeAddress"]'), row.find('./column[@name="Candidate.GivenName"]'), row.find('./column[@name="Candidate.Phone"]')] #insert the data into a line line = [] for item in items: if item is None: line.append("") else: try: line.append(item.t
🌐
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")
Find elsewhere
🌐
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 ...
Starred by 23 users
Forked by 7 users
Languages   Python
🌐
Stack Overflow
stackoverflow.com › questions › 65322142 › how-to-convert-an-xml-to-csv-dynamically
python - How to convert an xml to csv dynamically - Stack Overflow
You may want to flattened the dictionary or allow for repeating data? ... import csv import xmltodict def save_dict_to_csv(filename, dict): with open(filename, 'w') as csvfile: w = csv.DictWriter(csvfile, dict.keys()) w.writeheader() w.writerow(dict) xml = r""" <Process> <ProcessName>Vault-2-A</ProcessName> <ProcessEnabled>True</ProcessEnabled> <ProcessType>N2N</ProcessType> <NonDuplicationMethod>Delete</NonDuplicationMethod> <OnFileExistsInDest>Overwrite</OnFileExistsInDest> <ProcessScheduling>ExternalActivation</ProcessScheduling> <ExternalActivationLevel>Process</ExternalActivationLevel> <P
🌐
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)
🌐
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.
Top answer
1 of 2
1

Try the following

from bs4 import BeautifulSoup as bs

data = list()

with open("data.xml") as xml:
    data_xml = bs(xml, "html.parser")
    for record in data_xml.find_all("record"):
        for ts in record.find_all("ts"):
            id_, date, time, value = record.get("id"), ts.get("date"), ts.get("time"), ts.text
            data.append(", ".join([id_, date, time, value]) + "\n")

with open("data.csv", "w") as csv:
    csv.write("ID, date, time, value\n")
    csv.writelines(data)
2 of 2
0

To use lxml, you can simply pass the string as html(). By using the xpath //record/ts (starting with double backslash), you can fetch all your ts results. The main id can be accessed by calling .getparent() and then the attribute.

To convert xml to csv, I would recommend using the python package csv. You can use normal file writer. However csv write handles a lot of issues and it's cleaner.

In general, you have one method that handles everything. I would recommend splitting the logic into functions. Think Single Responsibility. Also the solution below I've converted the xml nodes into a NamedTupple and then write the namedTupple to csv. It's a lot easier to maintain/ read. (i.e Theres one place that sets the header text and one place populate the data).

from lxml import etree
import csv #py -m pip install python-csv
import collections
from collections import namedtuple

Record = namedtuple('Record', ['id', 'date', 'time', 'value']) # Model to store records.

def CreateCsvFile(results):
    with open('results.csv', 'w', newline='') as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=list(Record._fields)) # use the namedtuple fields for the headers 
        writer.writeheader()
        writer.writerows([x._asdict() for x in results]) # To use DictWriter, the namedtuple has to be converted to dictionary

def FormatRecord(xmlNode):
    return Record(xmlNode.getparent().attrib['id'], xmlNode.attrib["date"], xmlNode.attrib["time"], xmlNode.text)

def Main(html):
    xmlTree = etree.HTML(html)
    results = [FormatRecord(xmlNode) for xmlNode in xmlTree.xpath('//record/ts')] # the double backslash will retrieve all nodes for record.
    CreateCsvFile(results)

if __name__ == '__main__':
    Main("""<record id="idOne">
            <ts date="2019-07-03" time="15:28:41.720440">5</ts>
            <ts date="2019-07-03" time="15:28:42.629959">10</ts>
            <ts date="2019-07-03" time="15:28:43.552677">15</ts>
            <ts date="2019-07-03" time="15:28:43.855345">20</ts>
        </record>

        <record id="idTwo">
            <ts date="2019-07-03" time="15:28:45.072922">30</ts>
            <ts date="2019-07-03" time="15:28:45.377087">35</ts>
            <ts date="2019-07-03" time="15:28:46.316321">40</ts>
            <ts date="2019-07-03" time="15:28:47.527960">45</ts>
        </record>""")
🌐
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.
🌐
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.
🌐
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 - Libraries like XML.etree take care of XML parsing and CSV formatting details. 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.
🌐
Like Geeks
likegeeks.com › home › python › pandas › export xml to csv using python pandas
Export XML to CSV using Python Pandas
December 16, 2023 - Learn how to convert XML to CSV using Pandas in Python, From handling simple to complex nested XML structures efficiently.
🌐
TryCatchDebug
trycatchdebug.net › news › 1405868 › generating-xsd-xml-and-csv-with-python
Dynamically Generating XSD, XML, and CSV Files using Python without Hardcoding Structure
October 9, 2024 - In this article, we will explore how to generate XSD, XML, and CSV files dynamically using Python without hardcoding their structures. We will be using the pandas and lxml libraries for this task.