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.
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
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)
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("<", "<") # Escape '<'
.replace(">", ">") # 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"
)
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()
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("&", '&') # Escape the '&' character
.replace("<", "<") # Escape the '<' character
.replace(">", ">") # 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()
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.
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.