Convert XML to CSV Using Python

Convert XML to CSV Using Python

XML or Extensible Markup Language is a markup language that stores data in a document in both human-readable and machine-readable format. It has a file extension, .xml.

CSV or Comma Separated Values stores data in a document separated by a comma. It has a file extension, .csv. In this article, we will learn how to convert XML data to CSV data using Python.

Convert XML to CSV Using Python

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. It has a method parse() that accepts an XML document as a parameter.

It parses the whole XML document and stores it in the form of a tree. The tree has a getroot() method that returns the root element of the tree.

Using a for loop, we can iterate over the tree and access the data using the tag names (name, rollnumber, and age).

To understand the conversion, we need some sample XML data. You can use the following XML data and store it in a file named input.xml.

The following code snippet will use this data, and you should too so that we are on the same page.

        <name>Rick Grimes</name>
        <name>Lori Grimes</name>
        <name>Carl Grimes</name>
        <name>Judith Grimes</name>

Refer to the following Python code to learn how to perform the conversion.

from xml.etree import ElementTree

tree = ElementTree.parse("input.xml")
root = tree.getroot()

for student in root:
    name = student.find("name").text
    roll_number = student.find("rollnumber").text
    age = student.find("age").text


Rick Grimes,1,15
Lori Grimes,2,16
Carl Grimes,3,14
Judith Grimes,4,13
Vaibhav Vaibhav avatar Vaibhav Vaibhav avatar

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.

LinkedIn GitHub

Related Article - Python XML

  • Pretty Print XML Output Pretty in Python
  • Create an XML Parser in Python
  • Convert XML to Dictionary in Python
  • Convert XML to JSON in Python
  • Related Article - Python CSV

  • Python Split CSV Into Multiple Files
  • Compare Two CSV Files and Print Differences Using Python
  • Convert XLSX to CSV File in Python
  • Write List to CSV Columns in Python
  • Python Write to CSV Line by Line
  • Read CSV Line by Line in Python