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.

<students>
    <student>
        <name>Rick Grimes</name>
        <rollnumber>1</rollnumber>
        <age>15</age>
    </student>
    <student>
        <name>Lori Grimes</name>
        <rollnumber>2</rollnumber>
        <age>16</age>
    </student>
    <student>
        <name>Carl Grimes</name>
        <rollnumber>3</rollnumber>
        <age>14</age>
    </student>
    <student>
        <name>Judith Grimes</name>
        <rollnumber>4</rollnumber>
        <age>13</age>
    </student>
</students>

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
    print(f"{name},{roll_number},{age}")

Output:

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