Use the csv module not lxml module to write rows to csv file. But still use lxml to parse and extract content from xml file:

import xml.etree.ElementTree as ET
import csv

tree = ET.parse('registerreads_EE.xml')

root = tree.getroot()[3]

with open('registerreads_EE.csv', 'w', newline='') as r:
    writer = csv.writer(r)
    writer.writerow(['read', 'date', 'entityid'])  # WRITING HEADERS

    for channel in tree.iter('Channel'):
        for exportrequest in channel.iter('ExportRequest'):
            entityid = exportrequest.attrib.get('EntityID')
            for meterread in channel.iter('Reading'):
                read = meterread.attrib.get('Value')
                date = meterread.attrib.get('ReadingTime')    

                # WRITE EACH ROW ITERATIVELY 
                writer.writerow([read[:-2],date[:10],entityid])  
Answer from Parfait on Stack Overflow
🌐
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 - Python offers native libraries to handle both XML and CSV. For our journey, we’ll use the xml.etree.ElementTree for parsing XML content and the csv module for CSV operations.
People also ask

How to Convert XML to CSV via Python?
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. Here is the code to convert XML to CSV via Python.
🌐
pdf.wondershare.com
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
What is CSV Format?
Released in 2005 the CSV or the Comma Separated Values are the ones which can be used to store tabular data with ease and satisfaction. The RFC 4180 standard is used to standardize the values of the CSV format. There are many character sets that can be used to denote the CSV formatting. It includes the ASCII, Unicode, EBCDIC, and Shift JIS. The main part of the CSV file is the record handling which is highly regarded by users all over the world. One record per file can be stored with ease. The sequence of fields also remains the same in CSV format.
🌐
pdf.wondershare.com
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
How do I convert an XML file to Excel?
If you need a smart and easy solution to convert XML to Excel format, try Wondershare PDFelement. It's an AI-powered software that aims to enhance your workflow with easy processing. To know how easily it works, look into the steps next: Step 1: Launch PDFelement and click the "+" icon from the top-left side. Then, choose "From File" and open your XML file. Step 2: Now, tap the "File" from the top toolbar and select the "Export To" option. From the extended menu, click the "Excel" option and eventually the "Save" button to get the file converted into Excel.
🌐
pdf.wondershare.com
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
🌐
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.
🌐
Roy Tutorials
roytuts.com › home › python › how to convert xml to csv using python
How to convert XML to CSV using Python - Roy Tutorials
February 25, 2024 - Both XML and CSV formats being language agnostic are widely used in different purpose for their easy support in different places while communicating with various systems. ... First thing is to import the required Python module, i.e., xml.etree.
🌐
Delft Stack
delftstack.com › home › howto › python › xml to csv python
How to Convert XML to CSV Using Python | Delft Stack
February 2, 2024 - To convert XML to CSV, we can use the in-built xml module in Python. This module has yet another module, ElementTree, that we can use to represent an XML document as a tree.
🌐
Experts Exchange
experts-exchange.com › questions › 28769560 › Python-ElementTree-xml-output-to-csv.html
Solved: Python ElementTree xml output to csv | Experts Exchange
October 11, 2010 - #!python2 import xml.etree.ElementTree as ET import csv tree = ET.parse('registerreads_EE.xml') root = tree.getroot() with open('registerreads_EE.csv', 'wb') as fout: writer = csv.writer(fout) row = ['read', 'date', 'entityid'] writer.writerow(row) for channel in root.findall('.//Channel'): exportrequest = channel.find('ExportRequest') entityid = exportrequest.attrib.get('EntityID') for reading in channel.findall('Readings/Reading'): value = reading.attrib.get('Value') reading_time = reading.attrib.get('ReadingTime') row = [value[:-2], reading_time[:10], entityid] print ', '.join(row) writer.writerow(row)
🌐
Python Pool
pythonpool.com › home › blog › xml to csv conversion using python
XML to CSV Conversion Using Python - Python Pool
April 11, 2025 - Hello coders!! In this article we will learn how to convert an xml file into a csv file in python. So without much ado lets directly dive into the topic.
Find elsewhere
🌐
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
June 14, 2021 - Step 1. Simply open Python and paste the given code there. # Importing the required libraries import xml.etree.ElementTree as Xet import pandas as pd cols = ["name", "phone", "email", "date", "country"] rows = [] # Parsing the XML file xmlparse = Xet.parse('sample.xml') root = xmlparse.getroot() for i in root: name = i.find("name").text phone = i.find("phone").text email = i.find("email").text date = i.find("date").text country = i.find("country").text rows.append({"name": name, "phone": phone, "email": email, "date": date, "country": country}) df = pd.DataFrame(rows, columns=cols) # Writing dataframe to csv df.to_csv('output.csv')
🌐
Linux Hint
linuxhint.com › python-xml-to-csv
Python XML to CSV
Linux Hint LLC, [email protected] 1210 Kelly Park Circle, Morgan Hill, CA 95037 Privacy Policy and Terms of Use
🌐
Python
docs.python.org › 3 › library › xml.etree.elementtree.html
xml.etree.ElementTree — The ElementTree XML API
January 29, 2026 - Source code: Lib/xml/etree/ElementTree.py The xml.etree.ElementTree module implements a simple and efficient API for parsing and creating XML data. Tutorial: This is a short tutorial for using xml....
🌐
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 - In this blog post, we’ll guide you through the process of converting complex XML files to Pandas DataFrame/CSV using Python · By Saturn Cloud | Monday, July 10, 2023 | Miscellaneous | Updated: Thursday, 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 › @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
January 6, 2026 - 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.
🌐
Quora
quora.com › How-do-you-convert-XML-to-CSV-in-Python
How to convert XML to CSV in Python - Quora
April 4, 2023 - 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”, ...
Top answer
1 of 1
2

You could create a list containing all the mappings you want. Try and search for each, and if it is not present, catch the AttributeError and store an empty value for it:

import xml.etree.ElementTree as ET
import csv

fields = [
    ('Id_Customer', 'Id_Customer'),
    ('Segment', 'Segment'),
    ('Nature', 'Event/Nature'),
    ('Extrainfo', 'Event/Extrainfo'),
    ('zipcode', 'Adress/zipcode'),
    ('street', 'Adress/street'),
    ('number', 'Adress/number')]

tree = ET.parse('cat.xml')
root = tree.getroot()

with open(r'customerdata.csv', 'wb') as f_customerdata:
    csv_customerdata = csv.DictWriter(f_customerdata, fieldnames=[field for field, match in fields])
    csv_customerdata.writeheader()

    for node in tree.iter('Customer'):
        row = {}

        for field_name, match in fields:
            try:
                row[field_name] = node.find(match).text
            except AttributeError as e:
                row[field_name] = ''

        csv_customerdata.writerow(row)

Giving you an output CSV file containing:

Id_Customer,Segment,Nature,Extrainfo,zipcode,street,number
xyz1,abc1,info1,info2,,,
zzwy,c2,,,77098,belaire drive,5

This approach also uses a DictWriter() instead of the standard csv writer. This makes it easier to assign values by name.


To cope with multiple address entries per customer, you first need to autocreate the maximum number of extra columns per entry. Then when accessing the elements, use findall() to get each one:

import xml.etree.ElementTree as ET
import csv

extra_columns = 2

fields = [
    ('Id_Customer', 'Id_Customer', 1),
    ('Segment', 'Segment', 1),
    ('Nature', 'Event/Nature', 1),
    ('Extrainfo', 'Event/Extrainfo', 1),
    ('zipcode', 'Adress/zipcode', extra_columns),
    ('street', 'Adress/street', extra_columns),
    ('number', 'Adress/number', extra_columns)]

tree = ET.parse('cat.xml')
root = tree.getroot()

# Auto create the header from fields
fieldnames = []

for field, match, cols in fields:
    fieldnames.append(field)

    if cols > 1:
        fieldnames.extend(["{}{}".format(field, x+2) for x in range(extra_columns)])

with open(r'customerdata.csv', 'wb') as f_customerdata:
    csv_customerdata = csv.DictWriter(f_customerdata, fieldnames=fieldnames)
    csv_customerdata.writeheader()

    for node in tree.iter('Customer'):
        row = {}

        for field_name, match, cols in fields:
            if cols > 1:
                for index, el in enumerate(node.findall(match)):
                    try:
                        if index:
                            row["{}{}".format(field_name, index+1)] = el.text
                        else:
                            row[field_name] = el.text

                    except AttributeError as e:
                        row[field_name] = ''
            else:
                try:
                    row[field_name] = node.find(match).text
                except AttributeError as e:
                    row[field_name] = ''

        csv_customerdata.writerow(row)

So your header would now look like:

Id_Customer,Segment,Nature,Extrainfo,zipcode,zipcode2,zipcode3,street,street2,street3,number,number2,number3
🌐
ActiveState
code.activestate.com › recipes › 577423-convert-csv-to-xml
Convert CSV to XML « Python recipes « ActiveState Code
October 11, 2010 - import csv from collections import OrderedDict import xml.etree.ElementTree import re import os.path import os
🌐
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 - Python is as popular as ever in data science, which is why this task is made relatively easy from a programmer’s perspective. It has libraries like Pandas and XML.etree that are used especially to manipulate the data. 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 ...
🌐
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
September 15, 2024 - 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.