Sabtu, 18 April 2026

Python XML 1

 



import tkinter as tk

from tkinter import ttk, messagebox

import xml.etree.ElementTree as ET

import os


# ---------------------------

# Load XML Data Function

# ---------------------------

def load_xml_data(file_path):

    """Load and parse XML data into a list of dictionaries."""

    if not os.path.exists(file_path):

        messagebox.showerror("Error", f"File not found: {file_path}")

        return []


    try:

        tree = ET.parse(file_path)

        root = tree.getroot()


        data_list = []

        for item in root.findall("record"):

            record_data = {

                "ID": item.findtext("id", "").strip(),

                "Name": item.findtext("name", "").strip(),

                "Age": item.findtext("age", "").strip(),

                "City": item.findtext("city", "").strip()

            }

            data_list.append(record_data)

        return data_list

    except ET.ParseError as e:

        messagebox.showerror("XML Parse Error", str(e))

        return []


# ---------------------------

# Search Function

# ---------------------------

def search_data():

    """Filter table based on search query."""

    query = search_var.get().lower().strip()

    table.delete(*table.get_children())  # Clear table


    for row in xml_data:

        if query in row["Name"].lower() or query in row["City"].lower():

            table.insert("", tk.END, values=(row["ID"], row["Name"], row["Age"], row["City"]))


# ---------------------------

# Main Tkinter Window

# ---------------------------

root = tk.Tk()

root.title("XML Search & Display")

root.geometry("600x400")


# Search Input

search_var = tk.StringVar()

tk.Label(root, text="Search:").pack(pady=5)

search_entry = tk.Entry(root, textvariable=search_var, width=40)

search_entry.pack(pady=5)

tk.Button(root, text="Search", command=search_data).pack(pady=5)


# Table (Treeview)

columns = ("ID", "Name", "Age", "City")

table = ttk.Treeview(root, columns=columns, show="headings")

for col in columns:

    table.heading(col, text=col)

    table.column(col, width=100)

table.pack(fill=tk.BOTH, expand=True, pady=10)


# Load XML Data

xml_file = "data.xml"  # Change to your XML file path

xml_data = load_xml_data(xml_file)


# Display all data initially

for row in xml_data:

    table.insert("", tk.END, values=(row["ID"], row["Name"], row["Age"], row["City"]))


root.mainloop()



=========================


data.xml


<?xml version="1.0"?>

<records>

    <record>

        <id>1</id>

        <name>John Doe</name>

        <age>30</age>

        <city>New York</city>

    </record>

    <record>

        <id>2</id>

        <name>Jane Smith</name>

        <age>25</age>

        <city>Los Angeles</city>

    </record>

    <record>

        <id>3</id>

        <name>Michael Brown</name>

        <age>40</age>

        <city>Chicago</city>

    </record>

</records>

Tidak ada komentar: