CSV to XML Converter with Tkinter


CSV file to XML using pandas

This tutorial demonstrates how to create a simple and user-friendly Python application using Tkinter to convert CSV files into XML format. You'll learn how to build a GUI that allows users to browse CSV files, process their data, and save the output as XML files.


How to Convert CSV to XML Using Python with #tkinter and Pandas | Step-by-Step Guide #dataexport

Code Breakdown

1. Imports and Initial Setup

import tkinter as tk  # Tkinter for GUI
from tkinter import filedialog  # File dialog for browsing
import pandas as pd  # pandas for CSV processing
import xml.etree.ElementTree as ET  # For XML generation

2. Function to Browse File

def browse_file():
    # Open file dialog to select a CSV file
    file_path = filedialog.askopenfilename(filetypes=[("CSV files", "*.csv")])
    if file_path:
        lbl_csv.config(text=f"Selected File: {file_path}")
        convert_to_xml(file_path)
  • Purpose: Allows users to browse and select a CSV file using a file dialog.
  • Key Action: Calls the convert_to_xml function to process the selected file.

3. Function to Convert CSV to XML

def convert_to_xml(file_path):
    # Try block for handling errors
    try:
        df = pd.read_csv(file_path)  # Read the CSV file into a DataFrame
        root = ET.Element("Root")  # Create root element

        for _, row in df.iterrows():
            row_element = ET.SubElement(root, "Row")
            for col_name, value in row.items():
                col_element = ET.SubElement(row_element, col_name)

                if pd.isna(value):  # Handle missing values
                    col_element.text = ""
                else:
                    col_element.text = (
                        str(value)
                        .replace("&", "&")  # Escape '&'
                        .replace("<", "&lt;")   # Escape '<'
                        .replace(">", "&gt;")   # Escape '>'
                    )

        save_path = filedialog.asksaveasfilename(
            defaultextension=".xml", 
            filetypes=[("XML files", "*.xml")]
        )
        if save_path:
            tree.write(
                save_path, 
                encoding="utf-8", 
                xml_declaration=True
            )
            lbl_status.config(
                text=f"XML File Saved: {save_path}", 
                fg="green"
            )
        else:
            lbl_status.config(
                text="Save operation cancelled.", 
                fg="orange"
            )
    except Exception as e:
        lbl_status.config(
            text=f"Error: {str(e)}", 
            fg="red"
        )
  • Purpose: Processes the selected CSV file, converts its data into XML format, and saves the XML file.
  • Features: Handles missing values, escapes special characters, and ensures robust error handling.

4. Main Application Window

my_w = tk.Tk()
my_w.geometry("500x200")
my_w.title("CSV to XML Converter")

lbl_title = tk.Label(my_w, text="CSV to XML Converter", font=("Arial", 14))
lbl_title.grid(row=0, column=0, columnspan=2, pady=10)

btn_browse = tk.Button(my_w, text="Browse CSV", command=browse_file, width=15)
btn_browse.grid(row=1, column=0, pady=10, padx=10)

lbl_csv = tk.Label(my_w, text="No file selected", width=50, anchor="w")
lbl_csv.grid(row=1, column=1, pady=10, padx=10)

lbl_status = tk.Label(my_w, text="", width=50, anchor="w", fg="blue")
lbl_status.grid(row=2, column=0, columnspan=2, pady=10)

my_w.mainloop()
  • Purpose: Sets up the Tkinter GUI with a title, buttons, and status labels.
  • Key Components: Includes interactive widgets like labels and buttons for a user-friendly experience.


import tkinter as tk
from tkinter import filedialog
import pandas as pd
import xml.etree.ElementTree as ET


# Function to browse CSV file
def browse_file():
    file_path = filedialog.askopenfilename(filetypes=[("CSV files", "*.csv")])
    if file_path:
        lbl_csv.config(text=f"Selected File: {file_path}")
        convert_to_xml(file_path)


# Function to convert CSV to XML and save
def convert_to_xml(file_path):
    try:
        # Read CSV
        df = pd.read_csv(file_path)

        # Create root element
        root = ET.Element("Root")

        # Add rows as XML elements
        for _, row in df.iterrows():
            row_element = ET.SubElement(root, "Row")
            for col_name, value in row.items():
                col_element = ET.SubElement(row_element, col_name)

                # Convert to string and escape special characters
                if pd.isna(value):  # Handle missing values
                    col_element.text = ""
                else:
                    # Convert to string and escape special characters
                    col_element.text = (
                        str(value)
			.replace("&", '&amp;')  # Escape the '&' character
			.replace("<", "&lt;")   # Escape the '<' character
			.replace(">", "&gt;")   # Escape the '>' character
			)



        # Generate XML string
        tree = ET.ElementTree(root)

        # Save XML file
        save_path = filedialog.asksaveasfilename(defaultextension=".xml", 
                            filetypes=[("XML files", "*.xml")])
        if save_path:
            tree.write(save_path, encoding="utf-8", xml_declaration=True)
            lbl_status.config(text=f"XML File Saved: {save_path}", fg="green")
        else:
            lbl_status.config(text="Save operation cancelled.", fg="orange")

    except Exception as e:
        lbl_status.config(text=f"Error: {str(e)}", fg="red")


# Tkinter GUI setup
my_w = tk.Tk()
my_w.geometry("500x200")
my_w.title("CSV to XML Converter")

# Widgets
lbl_title = tk.Label(my_w, text="CSV to XML Converter", font=("Arial", 14))
lbl_title.grid(row=0, column=0, columnspan=2, pady=10)

btn_browse = tk.Button(my_w, text="Browse CSV", command=browse_file, width=15)
btn_browse.grid(row=1, column=0, pady=10, padx=10)

lbl_csv = tk.Label(my_w, text="No file selected", width=50, anchor="w")
lbl_csv.grid(row=1, column=1, pady=10, padx=10)

lbl_status = tk.Label(my_w, text="", width=50, anchor="w", fg="blue")
lbl_status.grid(row=2, column=0, columnspan=2, pady=10)

my_w.mainloop()

CSV to XML using pd.read_csv() and pd.to_xml()

We are not using Tkinter GUI here, you can update the input and output file path and export the data.
read_csv() : Read CSV file and create Pandas DataFrame
to_xml() : From Pandas DataFrame create xml file.

import pandas as pd

# Step 1: Define input and output file paths
input_csv = "E:\\testing\\data.csv"  # Replace with your CSV file path
output_xml = "E:\\testing\\data.xml"  # Desired XML file name

# Step 2: Read the CSV file into a Pandas DataFrame
df = pd.read_csv(input_csv)
# 'read_csv()' loads the CSV file specified by 'input_csv' into a DataFrame 'df'.

# Step 3: Export the DataFrame to an XML file
df.to_xml(output_xml, index=False, root_name="data", row_name="record")
# 'to_xml()' converts the DataFrame 'df' into an XML file with specified parameters:
# - 'index=False': Excludes the index from the XML output.
# - 'root_name="data"': Sets the root element name in the XML to 'data'.
# - 'row_name="record"': Tags each row in the XML as 'record'.

# Step 4: Confirmation message
print(f"CSV data successfully converted to XML and saved as {output_xml}.")
# Prints a message confirming the XML file creation.

Conclusion

With this application, you can efficiently convert CSV files to XML format using Python and Tkinter. The GUI simplifies the process, making it accessible for users of all skill levels.


Export Excel file to XML file by using Dataframe
Export SQLite database table data to CSV file by using Dataframe
Tkinter Projects Projects Tkinter using Pandas DataFrame

Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer