Untitled
unknown
plain_text
2 years ago
3.1 kB
9
Indexable
import tkinter as tk
from tkinter import filedialog
import xml.dom.minidom
from os.path import dirname, join, basename, splitext
def import_file(file_name):
try:
with open(file_name, 'r') as file:
content = file.read()
return content
except FileNotFoundError:
print(f"File '{file_name}' not found.")
return None
def write_output(content, output_file_name):
try:
with open(output_file_name, 'w') as file:
file.write(content)
print(f"Content written to '{output_file_name}' successfully.")
except Exception as e:
print(f"Error {e} occurred while writing to '{output_file_name}'.")
def select_file():
file_path = filedialog.askopenfilename()
entry_file.delete(0, tk.END)
entry_file.insert(0, file_path)
def process_files():
input_file = entry_file.get()
output_name = entry_output.get()
if output_name == "" or output_name is None:
output_name = basename(input_file)
file_name_without_ext, file_ext = splitext(output_name)
output_name = f"{file_name_without_ext}_formated"
with open(input_file, "r", encoding="utf-8") as file:
xml_string = file.read()
dom = xml.dom.minidom.parseString(xml_string)
formatted_xml = format_xml(dom.documentElement)
input_path = dirname(input_file)
output_file = join(input_path, output_name)
if output_file[-3:] == "txt":
write_output(formatted_xml, output_file)
else:
output_file += ".txt"
write_output(formatted_xml, output_file)
def get_element_text(element):
if element.childNodes and element.childNodes[0].nodeType == element.TEXT_NODE:
return element.childNodes[0].nodeValue.strip()
else:
return ""
def format_xml(element, indent=""):
name = element.getAttribute("name") # Get the value of the "name" attribute
if name:
result = f"{indent}{name}: {get_element_text(element)}\n"
else:
result = f"{indent}{element.tagName}: {get_element_text(element)}\n"
for child in element.childNodes:
if child.nodeType == child.ELEMENT_NODE:
result += format_xml(child, indent + " ")
return result
# Create the main window
window = tk.Tk()
window.title("File Import")
# Create labels and entry fields
label_file = tk.Label(window, text="Input File:")
label_file.grid(row=0, column=0, padx=5, pady=5)
entry_file = tk.Entry(window, width=50)
entry_file.grid(row=0, column=1, padx=5, pady=5)
button_file = tk.Button(window, text="Select", command=select_file)
button_file.grid(row=0, column=2, padx=5, pady=5)
label_output = tk.Label(window, text="Output File:")
label_output.grid(row=1, column=0, padx=5, pady=5)
entry_output = tk.Entry(window, width=50)
entry_output.grid(row=1, column=1, padx=5, pady=5)
button_process = tk.Button(window, text="Process", command=process_files)
button_process.grid(row=2, column=0, columnspan=3, padx=5, pady=5)
# Start the main event loop
window.mainloop()Editor is loading...