How to convert a CSV file to XML with Python

Converting a CSV file to XML is a common task when working with structured data in Python. CSV files (Comma-Separated Values) are widely used to store tabular data, while XML (eXtensible Markup Language) is extensively used to represent hierarchical and structured data in a format readable by both humans and machines. In this article, we will see how to perform this conversion using Python.

Python offers the csv library to read CSV files. Let's assume we have a CSV file called data.csv with the following content:


Name,Surname,Age
Mario,Rossi,30
Luigi,Bianchi,25
Anna,Verdi,22

Now let's create the main code:


import csv
import xml.etree.ElementTree as ET

def csv_to_xml(csv_file, xml_file):
    # Read the CSV file
    with open(csv_file, mode='r', newline='', encoding='utf-8') as file:
        csv_reader = csv.DictReader(file)
        
        # Create the XML root
        root = ET.Element("Data")
        
        # Iterate through the CSV rows and create XML nodes
        for row in csv_reader:
            record = ET.SubElement(root, "Record")
            for key, value in row.items():
                element = ET.SubElement(record, key)
                element.text = value
        
        # Write the XML to file
        tree = ET.ElementTree(root)
        with open(xml_file, mode='wb') as xml_output:
            tree.write(xml_output, encoding='utf-8', xml_declaration=True)

# Run the function
csv_to_xml("data.csv", "data.xml")

Here's how the data.xml file looks:


<?xml version='1.0' encoding='utf-8'?>
<Data>
    <Record>
        <Name>Mario</Name>
        <Surname>Rossi</Surname>
        <Age>30</Age>
    </Record>
    <Record>
        <Name>Luigi</Name>
        <Surname>Bianchi</Surname>
        <Age>25</Age>
    </Record>
    <Record>
        <Name>Anna</Name>
        <Surname>Verdi</Surname>
        <Age>22</Age>
    </Record>
</Data>

Conclusion

Converting CSV to XML in Python is a relatively straightforward process thanks to Python's standard libraries. With the provided code, you can easily transform tabular data into custom XML structures to suit your needs.

Back to top