How to convert xml to csv file

0 votes
The data in xml file is someting like this:

<?xml version="1.0" encoding="utf-8"?>
<badges>
  <row Id="1" UserId="2" Name="Autobiographer" Date="2010-10-19T19:16:16.410" Class="3" TagBased="False" />
  <row Id="2" UserId="3" Name="Autobiographer" Date="2010-10-19T19:31:16.490" Class="3" TagBased="False" />
  <row Id="3" UserId="4" Name="Autobiographer" Date="2010-10-19T19:31:16.507" Class="3" TagBased="False" />
  <row Id="4" UserId="6" Name="Autobiographer" Date="2010-10-19T19:41:16.283" Class="3" TagBased="False" />
  <row Id="5" UserId="7" Name="Autobiographer" Date="2010-10-19T19:58:32.830" Class="3" TagBased="False" />

</badges>

I tried many times using ElementTree or xmltodict, but still fail to convert it. Could anyone please advise on this?

My script is as below:

xml = Xet.parse("Badges.xml")
root = xml.getroot()

csvfile = open("Badges.csv",'w',encoding='utf-8')
csvfile_writer = csv.writer(csvfile)

csvfile_writer.writerow(["Id", "UserId", "Name", "Date", "Class", "TagBased"])

for row in root.findall("row"):
    if(row):
        # EXTRACT DETAILS  
        Id = row.find("Id")
        UserId = row.find("UserId")
        Name = row.find("Name")
        Date = row.find("Date")
        Class = row.find("Class")
        TagBased = row.find("TagBased")
        csv_line = [Id.text, UserId.text, Name.text, Date.text, Class.text, TagBased.text]
        
        # ADD A NEW ROW TO CSV FILE
        csvfile_writer.writerow(csv_line)

csvfile.close()

Many thanks!

Erik
Jan 29, 2023 in Python by Wu

edited Mar 4, 2025 378 views

No answer to this question. Be the first to respond.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP