Page 1 of 1

Read xml column inside csv file with Python

Posted: Fri Jul 22, 2022 11:46 pm
by estertabita
Hi,
I am very new in Python and need to read an xml column inside a csv file with Python.
I can see some code on google on how to read that csv file but I don’t know how to read the xml column inside the csv file. Can someone help? any idea would be appreciated.

Thank you!

Re: Read xml column inside csv file with Python

Posted: Sun Aug 03, 2025 1:57 pm
by Kicoco
I'm a bit late, but it could help users falling on this post.

I think it should look something like this:

Code: Select all

import csv
import xml.etree.ElementTree as ET

# Open the CSV file
with open("your_file.csv", newline='', encoding='utf-8') as csvfile:
    # Create a CSV reader that gives each row as a dictionary
    reader = csv.DictReader(csvfile)
   
    # Iterate through each row of the CSV
    for row in reader:
        # Get the XML content from the specific column (replace with your actual column name)
        xml_data = row["xml_column"]
       
        # Parse the XML string into an ElementTree
        root = ET.fromstring(xml_data)
       
        # Iterate through all elements in the XML and print their tag and text
        for elem in root.iter():
            print(elem.tag, elem.text)