Convert XML to CSV in Python

Converting XML data to CSV format is a frequent requirement in data pipelines and analytics.

Python provides robust solutions ranging from high-level libraries like Pandas (`read_xml()`) to standard library modules like ElementTree paired with the `csv` module.

1. Sample XML File

Consider the following sample XML file, data.xml, containing structured records:

<data>
    <record>
        <id>1</id>
        <name>John Doe</name>
        <age>30</age>
        <city>New York</city>
    </record>
    <record>
        <id>2</id>
        <name>Jane Smith</name>
        <age>25</age>
        <city>Los Angeles</city>
    </record>
    <record>
        <id>3</id>
        <name>Emily Davis</name>
        <age>35</age>
        <city>Chicago</city>
    </record>
</data>

2. Using Pandas `read_xml()` to Convert XML to CSV

The Pandas library provides the read_xml() method to parse XML data into a DataFrame effortlessly, which can then be exported as a CSV file.

Code Example

import pandas as pd

# Input and output file paths
input_file = 'data.xml'
output_file = 'data.csv'

# Read the XML file into a Pandas DataFrame
df = pd.read_xml(input_file)

# Export the DataFrame to a CSV file
df.to_csv(output_file, index=False)

# Output confirmation
print(f"Data exported to {output_file} successfully.")

Explanation:

  • pd.read_xml(): Parses the XML file and loads it into a DataFrame.
  • df.to_csv(): Exports the DataFrame to a CSV file.
  • index=False: Prevents the DataFrame's index column from being included in the CSV file.

3. Using ElementTree and CSV Modules

The ElementTree module, part of Python’s standard library, allows you to parse XML files iteratively and write structured rows using the built-in csv module.

Code Example

import xml.etree.ElementTree as ET
import csv

# Input and output file paths
input_file = 'student.xml'
output_file = 'data.csv'

# Parse the XML file
tree = ET.parse(input_file)
root = tree.getroot()

# Extract data from XML
rows = []
headers = []

# Iterate through records
for record in root.findall('record'):
    row = {}
    for element in record:
        if element.tag not in headers:
            headers.append(element.tag)  # Collect headers dynamically
        row[element.tag] = element.text
    rows.append(row)

# Write data to CSV
with open(output_file, 'w', newline='', encoding='utf-8') as csvfile:  
    writer = csv.DictWriter(csvfile, fieldnames=headers)
    writer.writeheader()  # Write headers
    writer.writerows(rows)  # Write rows

print(f"Data exported to {output_file} successfully.")

Explanation:

  • ET.parse(): Parses the XML file and creates an ElementTree structure.
  • root.findall('record'): Locates all <record> elements within the XML document.
  • csv.DictWriter: Efficiently writes dictionary rows into a properly formatted CSV file.

4. Comparison of Methods

Feature Pandas `read_xml()` ElementTree + CSV
Ease of Use Very simple and concise Requires manual element iteration
Dependencies Requires Pandas Built into Python standard library
Customization Limited parsing options Full programmatic control over parsing
Performance Fast for flat, tabular XML Better for deeply nested custom schemas

5. Which Method Should You Use?

Use Pandas `read_xml()` when working on data science pipelines where Pandas is already imported and the XML structure is relatively flat.

Use ElementTree when building lightweight scripts that avoid heavy third-party dependencies or require custom data transformations during conversion.


Conclusion

Both methods are highly effective for converting XML to CSV in Python. Choose the approach that best fits your project environment and data complexity.

How to convert CSV data to XML file using Tkinter GUI and Pandas DataFrame

Interactive Notebook & Practice Exercises

Practice converting XML to CSV in our companion Jupyter Notebook:

Interactive Companion Jupyter Notebook

Explore interactive code cells and test converting XML files to CSV using both Pandas and ElementTree.

View on GitHub Open In Colab



Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer