-
Notifications
You must be signed in to change notification settings - Fork 0
/
XMLuvation.py
1615 lines (1291 loc) · 68.4 KB
/
XMLuvation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from PySide6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout,
QHBoxLayout, QTabWidget, QGroupBox, QLabel,
QLineEdit, QPushButton, QComboBox, QRadioButton,
QListWidget, QTextEdit, QProgressBar, QStatusBar,
QCheckBox,QMenu,QFileDialog, QMessageBox, QFrame,
QSpacerItem, QSizePolicy, QTableView, QHeaderView, QInputDialog)
from PySide6.QtGui import QIcon, QAction, QStandardItemModel, QStandardItem, QCloseEvent
from PySide6.QtCore import Qt, QThread, Signal, Slot, QSortFilterProxyModel, QObject, QFile, QTextStream
from pathlib import Path
from datetime import datetime
from lxml import etree as ET
import pandas as pd
import sys
import csv
import os
import re
import webbrowser
import json
import traceback
import multiprocessing
from functools import partial
from typing import List, Tuple, Dict
# TODO Fix exit code = 3221226356 (HEAP_MEMORY_CORRUPTION) (Seems to be a thread still running on exit thing)
class ConfigHandler:
def __init__(self):
self.config_dir = "_internal\\configuration"
self.config_file = os.path.join(self.config_dir, "config.json")
os.makedirs(self.config_dir, exist_ok=True)
self.config = self.load_config()
def load_config(self):
if os.path.exists(self.config_file):
try:
with open(self.config_file, 'r') as f:
return json.load(f)
except json.JSONDecodeError:
print(f"Warning: {self.config_file} is empty or contains invalid JSON. Using default configuration.")
return self.get_default_config()
def get_default_config(self):
return {"custom_paths": {}}
def save_config(self):
with open(self.config_file, 'w') as f:
json.dump(self.config, f, indent=4)
def add_custom_path(self, name, path):
self.config["custom_paths"][name] = path
self.save_config()
def get_custom_paths(self):
return self.config["custom_paths"]
def remove_custom_path(self, name):
if name in self.config["custom_paths"]:
del self.config["custom_paths"][name]
self.save_config()
class XMLParserThread(QObject):
finished = Signal(dict)
show_error_message = Signal(str, str)
def __init__(self, parent, xml_file):
super().__init__()
self.parent = parent
self.xml_file = xml_file
def run(self):
try:
tree = ET.parse(self.xml_file)
root = tree.getroot()
xml_string = ET.tostring(root, encoding="unicode", pretty_print=True)
tags = set()
tag_values = set()
attributes = set()
attribute_values = set()
for elem in root.iter():
tags.add(elem.tag)
if elem.text and elem.text.strip():
tag_values.add(elem.text.strip())
for attr, value in elem.attrib.items():
attributes.add(attr)
attribute_values.add(value)
result = {
'xml_string': xml_string,
'tags': sorted(tags),
'tag_values': sorted(tag_values),
'attributes': sorted(attributes),
'attribute_values': sorted(attribute_values)
}
except Exception as ex:
self.show_error_message.emit("An exception occurred", str(ex))
finally:
self.finished.emit(result)
# Standalone processing functions that can be pickled
def process_single_xml(filename: str, folder_path: str, xpath_expressions: List[str]) -> Tuple[List[Dict], int, int]:
"""Process a single XML file and return its results."""
final_results = []
file_total_matches = 0
file_path = os.path.join(folder_path, filename)
try:
tree = ET.parse(file_path)
root = tree.getroot()
except ET.XMLSyntaxError:
return [], 0, 0
except Exception:
return [], 0, 0
for expression in xpath_expressions:
result = root.xpath(expression)
match_count = len(result)
file_total_matches += match_count
pattern_text_or_attribute_end = r'(.*?/text\(\)$|.*?/@[a-zA-Z_][a-zA-Z0-9_]*$)'
match = re.match(pattern_text_or_attribute_end, expression)
ends_with_text_or_attribute = bool(match)
if result:
current_result = {"Filename": os.path.splitext(filename)[0]}
if not ends_with_text_or_attribute:
current_result["Matches"] = match_count
current_result["Expression"] = expression
else:
process_xpath_result(expression, result, current_result)
if current_result:
final_results.append(current_result)
return final_results, file_total_matches, 1 if file_total_matches > 0 else 0
def process_xpath_result(expression: str, result, current_file_results: Dict):
"""Process xpath results for a single expression."""
if "/@" in expression:
attribute_name = expression.split("@")[-1]
key = f"Attribute {attribute_name} Value"
current_file_results[key] = ";".join([elem.strip() for elem in result if elem.strip()])
elif "/text()" in expression:
tag_name = expression.split("/")[-2]
key = f"Tag {tag_name} Value"
current_file_results[key] = ";".join([elem.strip() for elem in result if elem.strip()])
elif "[@" in expression:
match = re.search(r"@([^=]+)", expression)
if match:
attribute_name = match.group(1).strip()
key = f"Attribute {attribute_name} Value"
current_file_results[key] = ";".join([elem.get(attribute_name) for elem in result if elem.get(attribute_name)])
class CSVExportThread(QObject):
# Signals
finished = Signal()
show_info_message = Signal(str, str)
show_error_message = Signal(str, str)
progress_updated = Signal(int)
output_set_text = Signal(str)
output_append = Signal(str)
def __init__(self, folder_containing_xml_files, list_of_xpath_filters, csv_output_path):
super().__init__()
self.folder_containing_xml_files = folder_containing_xml_files
self.list_of_xpath_filters = list_of_xpath_filters
self.csv_output_path = csv_output_path
self._is_running = True
def stop(self):
"""Method to stop the running task"""
self._is_running = False
def run(self):
try:
self.search_and_export()
except Exception as ex:
self.show_error_message.emit("An exception occurred", str(ex))
finally:
self.finished.emit()
def search_and_export(self):
try:
matching_results, total_matches_found, total_matching_files = self.evaluate_xml_files_matching(
self.folder_containing_xml_files, self.list_of_xpath_filters)
# Check if the thread is supposed to be running
if not self._is_running:
return
except Exception as ex:
tb = traceback.extract_tb(ex.__traceback__)
line_number = tb[-1].lineno
message = f"An exception of type {type(ex).__name__} occurred on line {line_number}. Arguments: {ex.args!r}"
self.show_error_message.emit("An exception occurred", message)
return
try:
if not matching_results:
self.show_info_message.emit("No matches found", "No matches found by searching with the added filters.")
self.output_set_text.emit("")
return
# Define headers excluding Index
headers = ["Filename"]
# Add all other headers excluding Filename
additional_headers = set()
for dic in matching_results:
additional_headers.update(key for key in dic.keys() if key != "Filename")
headers.extend(sorted(additional_headers))
with open(self.csv_output_path, "w", newline="", encoding="utf-8") as csvfile:
writer = csv.DictWriter(
csvfile,
fieldnames=headers,
delimiter=",",
extrasaction="ignore",
quotechar='"',
quoting=csv.QUOTE_ALL
)
writer.writeheader()
# Group results by filename
results_by_filename = {}
for match in matching_results:
filename = match["Filename"]
if filename not in results_by_filename:
results_by_filename[filename] = []
results_by_filename[filename].append(match)
# Process each file's results
for filename, file_matches in results_by_filename.items():
for match in file_matches:
# Handle value fields that might contain multiple values
value_fields = {k: v for k, v in match.items() if k != "Filename" and v}
if not value_fields: # If there are no values, write a single row
writer.writerow({
"Filename": filename
})
else:
# Split multiple values and write separate rows
max_len = max(len(str(v).split(";")) for v in value_fields.values())
for i in range(max_len):
row = {
"Filename": filename
}
has_data = False
for key, value in value_fields.items():
value_list = str(value).split(";")
if i < len(value_list):
row[key] = value_list[i].strip()
if row[key]: # Check if the value is not empty
has_data = True
if has_data: # Only write the row if it has data
writer.writerow(row)
# Emit completion signals
self.show_info_message.emit("Export Successful", "CSV export completed.")
self.output_set_text.emit(
f"Found {total_matching_files} files that have a total sum of {total_matches_found} matches."
)
except Exception as ex:
tb = traceback.extract_tb(ex.__traceback__)
line_number = tb[-1].lineno
message = f"An exception of type {type(ex).__name__} occurred on line {line_number}. Arguments: {ex.args!r}"
self.show_error_message.emit("An exception occurred", message)
finally:
self.finished.emit()
def evaluate_xml_files_matching(self, folder_containing_xml_files, list_of_xpath_expressions):
"""Evaluate XML files using multiprocessing."""
xml_files = [f for f in os.listdir(folder_containing_xml_files) if f.endswith(".xml")]
total_files = len(xml_files)
if not xml_files:
return [], 0, 0
# Calculate the number of processes to use (leave one core free)
num_processes = max(1, multiprocessing.cpu_count() - 1)
# Initialize multiprocessing variables
final_results = []
total_sum_matches = 0
total_matching_files = 0
try:
while self._is_running:
# Create a pool of processes
with multiprocessing.Pool(processes=num_processes) as pool:
# Create partial function with fixed arguments
process_func = partial(
process_single_xml,
folder_path=folder_containing_xml_files,
xpath_expressions=list_of_xpath_expressions,
)
# Process files and collect results
for i, (file_results, file_matches, matching_file) in enumerate(
pool.imap_unordered(process_func, xml_files)
):
if not self._is_running:
self.output_set_text.emit("Export task aborted successfully.")
pool.terminate()
return final_results, total_sum_matches, total_matching_files
final_results.extend(file_results)
total_sum_matches += file_matches
total_matching_files += matching_file
# Update progress
progress = int((i + 1) / total_files * 100)
self.progress_updated.emit(progress)
self.output_set_text.emit(f"Processing file {i + 1} of {total_files}")
return final_results, total_sum_matches, total_matching_files
except Exception as ex:
self.show_error_message.emit(
"Multiprocessing Error",
f"Error during multiprocessing: {str(ex)}"
)
return [], 0, 0
class MainWindow(QMainWindow):
progress_updated = Signal(int)
update_input_file_signal = Signal(str)
update_output_file_signal = Signal(str)
def __init__(self):
super().__init__()
self.setAttribute(Qt.WA_DeleteOnClose)
self.current_theme = "_internal\\theme\\dark_theme.qss" # Sets the global main theme from the file
self.config_handler = ConfigHandler()
self.eval_input_file = None
self.xpath_filters = []
self.xpath_listbox = QListWidget(self)
self.program_output = QTextEdit()
self.csv_export_thread = None
self.csv_export_worker = None
self.parse_xml_thread = None
self.parse_xml_worker = None
self.setWindowTitle("XMLuvation v1.3.1")
self.setWindowIcon(QIcon("_internal\\icon\\xml_256px.ico")) # Replace with actual path
self.setGeometry(500, 250, 1300, 840)
self.saveGeometry()
# Signals and Slots
self.progress_updated.connect(self.update_progress)
self.update_input_file_signal.connect(self.update_input_file)
self.update_output_file_signal.connect(self.update_output_file)
# Connect the custom context menu for Listbox
self.xpath_listbox.setContextMenuPolicy(Qt.CustomContextMenu)
self.xpath_listbox.customContextMenuRequested.connect(self.show_context_menu)
# Theme stuff
self.light_mode = QIcon("_internal\\images\\light.png")
self.dark_mode = QIcon("_internal\\images\\dark.png")
self.initUI()
# Create the menu bar
self.create_menu_bar()
try:
with open("_internal\\theme\\theme_config.txt", "r") as f:
self.initialize_theme(f.read())
if f.read() == "_internal\\theme\\light_theme.qss":
self.toggle_theme_action.setIcon(self.dark_mode)
else:
self.toggle_theme_action.setIcon(self.light_mode)
except FileNotFoundError:
self.initialize_theme(self.current_theme)
def initUI(self):
# Create the main layout
main_layout = QVBoxLayout()
# Create the tab widget
tab_widget = QTabWidget()
tab_widget.addTab(self.create_xml_evaluation_tab(), "XML Evaluation")
tab_widget.addTab(self.create_csv_conversion_tab(), "CSV Conversion and Display")
main_layout.addWidget(tab_widget)
# Create a central widget to hold the main layout
central_widget = QWidget()
central_widget.setLayout(main_layout)
self.setCentralWidget(central_widget)
def closeEvent(self, event: QCloseEvent):
reply = QMessageBox.question(
self, 'Exit Program', 'Are you sure you want to exit the program?',
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if reply == QMessageBox.Yes:
event.accept()
with open("_internal\\theme\\theme_config.txt", "w") as f:
f.write(self.current_theme)
else:
event.ignore()
def initialize_theme(self, theme_file):
try:
file = QFile(theme_file)
if file.open(QFile.ReadOnly | QFile.Text):
stream = QTextStream(file)
stylesheet = stream.readAll()
self.setStyleSheet(stylesheet)
file.close()
except Exception as ex:
message = f"An exception of type {type(ex).__name__} occurred. Arguments: {ex.args!r}"
QMessageBox.critical(self, "Theme load error", message)
def create_menu_bar(self):
menu_bar = self.menuBar()
# File Menu
file_menu = menu_bar.addMenu("&File")
clear_action = QAction("Clear Output", self)
clear_action.setStatusTip("Clear the output")
clear_action.triggered.connect(self.clear_output)
file_menu.addAction(clear_action)
file_menu.addSeparator()
exit_action = QAction("E&xit", self)
exit_action.setStatusTip("Exit the application")
exit_action.triggered.connect(self.close)
file_menu.addAction(exit_action)
# Open Menu
open_menu = menu_bar.addMenu("&Open")
open_input_action = QAction("Open XML Input Folder", self)
open_input_action.setStatusTip("Open the XML input folder")
open_input_action.triggered.connect(self.open_input_folder)
open_menu.addAction(open_input_action)
open_output_action = QAction("Open CSV Output Folder", self)
open_output_action.setStatusTip("Open the CSV output folder")
open_output_action.triggered.connect(self.open_output_folder)
open_menu.addAction(open_output_action)
open_menu.addSeparator()
open_csv_conversion_input_action = QAction("Open CSV Conversion Input Folder", self)
open_csv_conversion_input_action.setStatusTip("Open CSV Conversion Input Folder")
open_csv_conversion_input_action.triggered.connect(self.open_conversion_input)
open_menu.addAction(open_csv_conversion_input_action)
open_csv_conversion_output_action = QAction("Open CSV Conversion Output Folder", self)
open_csv_conversion_output_action.setStatusTip("Open CSV Conversion Output Folder")
open_csv_conversion_output_action.triggered.connect(self.open_conversion_output)
open_menu.addAction(open_csv_conversion_output_action)
# Path Menu
self.paths_menu = menu_bar.addMenu("&Path")
# Add custom paths
self.load_custom_paths()
# Add option to add new custom path
add_custom_path_action = QAction("Add Custom Path", self)
add_custom_path_action.triggered.connect(self.add_custom_path)
self.paths_menu.addAction(add_custom_path_action)
# Help Menu
help_menu = menu_bar.addMenu("&Help")
xpath_help_action = QAction("XPath Help", self)
xpath_help_action.setStatusTip("Open XPath Syntax Help")
xpath_help_action.triggered.connect(self.open_web_xpath_help)
help_menu.addAction(xpath_help_action)
about = QAction("About", self)
about.setStatusTip("About this program")
about.triggered.connect(self.about_message)
help_menu.addAction(about)
#help_menu.addAction(xpath_cheatsheet_action)
# Theme Menu
self.toggle_theme_action = menu_bar.addAction(self.light_mode, "Toggle Theme")
self.toggle_theme_action.triggered.connect(self.change_theme)
# ======= START FUNCTIONS create_menu_bar ======= #
def update_paths_menu(self):
# Clear existing path actions, except the last one (Add Custom Path)
for action in self.paths_menu.actions()[:-1]:
self.paths_menu.removeAction(action)
# Add custom paths
custom_paths = self.config_handler.get_custom_paths()
for name, path in custom_paths.items():
action = QAction(name, self)
action.setStatusTip(f"Open {name}")
action.triggered.connect(lambda checked, p=path: self.open_path(p))
self.paths_menu.insertAction(self.paths_menu.actions()[0], action)
def add_custom_path(self):
name, ok = QInputDialog.getText(self, "Add Custom Path", "Enter a name for the path:")
if ok and name:
path, ok = QInputDialog.getText(self, "Add Custom Path", "Enter path:")
if ok and path:
self.config_handler.add_custom_path(name, path)
self.update_paths_menu()
def load_custom_paths(self):
custom_paths = self.config_handler.get_custom_paths()
for name, path in custom_paths.items():
action = QAction(name, self)
action.setStatusTip(f"Open {name}")
action.triggered.connect(lambda checked, p=path: self.open_path(p))
self.paths_menu.addAction(action)
def about_message(self):
# About Message
program_info = "Name: XMLuvation\nVersion: 1.3.1\nCredit: Jovan\nFramework: PySide6"
about_message = """XMLuvation is a Python application designed to parse and evaluate XML files and use XPath to search for matches which matching results will be saved in a csv file. Radio buttons are disabled for now, this feature will be implemented in a later version."""
about_box = QMessageBox()
about_box.setText("About this program...")
about_box.setInformativeText(about_message)
about_box.setDetailedText(program_info)
about_box.exec()
def change_theme(self):
if self.current_theme == "_internal\\theme\\dark_theme.qss":
self.current_theme = "_internal\\theme\\light_theme.qss"
self.toggle_theme_action.setIcon(self.dark_mode)
else:
self.current_theme = "_internal\\theme\\dark_theme.qss"
self.toggle_theme_action.setIcon(self.light_mode)
self.initialize_theme(self.current_theme)
def clear_output(self):
self.program_output.clear()
self.csv_conversion_output.clear()
# Open XML input folder function
def open_input_folder(self):
directory_path = self.folder_xml_input.text()
if os.path.exists(directory_path):
try:
os.startfile(directory_path)
except Exception as ex:
message = f"An exception of type {type(ex).__name__} occurred. Arguments: {ex.args!r}"
QMessageBox.critical(self, "An exception occurred", message)
else:
QMessageBox.warning(self, "Error", f"Path does not exist or is not a valid path:\n{directory_path}")
# Open CSV output folder function
def open_output_folder(self):
directory_path = self.folder_csv_output.text()
if os.path.exists(directory_path):
try:
os.startfile(directory_path)
except Exception as ex:
message = f"An exception of type {type(ex).__name__} occurred. Arguments: {ex.args!r}"
QMessageBox.critical(self, "An exception occurred", message)
else:
QMessageBox.warning(self, "Error", f"Path does not exist or is not a valid path:\n{directory_path}")
def open_conversion_input(self):
directory_path = self.input_csv_file_conversion.text()
dirname = os.path.dirname(directory_path)
if os.path.exists(directory_path):
try:
os.startfile(dirname)
except Exception as ex:
message = f"An exception of type {type(ex).__name__} occurred. Arguments: {ex.args!r}"
QMessageBox.critical(self, "An exception occurred", message)
else:
QMessageBox.warning(self, "Error", f"Path does not exist or is not a valid path:\n{directory_path}")
def open_conversion_output(self):
directory_path = self.output_csv_file_conversion.text()
if os.path.exists(directory_path):
try:
os.startfile(directory_path)
except Exception as ex:
message = f"An exception of type {type(ex).__name__} occurred. Arguments: {ex.args!r}"
QMessageBox.critical(self, "An exception occurred", message)
else:
QMessageBox.warning(self, "Error", f"Path does not exist or is not a valid path:\n{directory_path}")
def open_path(self,path):
self.folder_xml_input.setText(path)
def open_web_xpath_help(self):
webbrowser.open("https://www.w3schools.com/xml/xpath_syntax.asp")
# ======= END FUNCTIONS create_menu_bar ======= #
def create_xml_evaluation_tab(self):
tab = QWidget()
layout = QHBoxLayout()
# Left column
left_column = QVBoxLayout()
left_column.addWidget(self.create_xml_eval_group())
left_column.addWidget(self.create_matching_filter_group())
left_column.addWidget(self.create_export_evaluation_group())
left_column.addWidget(self.create_program_output_group())
# Right column
right_column = QVBoxLayout()
right_column.addWidget(self.create_xml_output_group())
layout.addLayout(left_column, 1)
layout.addLayout(right_column, 1)
tab.setLayout(layout)
return tab
def create_xml_eval_group(self):
group = QGroupBox("XML FOLDER SELECTION AND XPATH BUILDER")
layout = QVBoxLayout()
xml_input_folder_and_statusbar_layout = QHBoxLayout()
# Elements
self.total_xml_files_statusbar = QStatusBar()
self.setStatusBar(self.total_xml_files_statusbar)
self.total_xml_files_statusbar.setSizeGripEnabled(False)
self.total_xml_files_statusbar.setStyleSheet("font-size: 20;font-weight: bold; color: #0cd36c")
xml_input_folder_and_statusbar_layout.addWidget(self.total_xml_files_statusbar)
layout.addLayout(xml_input_folder_and_statusbar_layout)
# Elements
self.folder_xml_input = QLineEdit()
self.folder_xml_input.setPlaceholderText("Choose a folder that contains XML files...")
self.folder_xml_input.textChanged.connect(self.update_xml_file_count)
self.browse_xml_folder_button = QPushButton("BROWSE")
self.browse_xml_folder_button.clicked.connect(self.browse_folder)
self.read_xml_button = QPushButton("READ XML")
self.read_xml_button.setToolTip("Writes the content of the selected XML file to the output and fills out the ComboBoxes based on the XMLs content.")
self.read_xml_button.clicked.connect(self.read_xml)
folder_layout = QHBoxLayout()
folder_layout.addWidget(self.folder_xml_input)
folder_layout.addWidget(self.browse_xml_folder_button)
folder_layout.addWidget(self.read_xml_button)
layout.addLayout(folder_layout)
layout.addSpacerItem(QSpacerItem(2,5, QSizePolicy.Expanding, QSizePolicy.Minimum))
layout.addWidget(QLabel("Get XML Tag and Attribute Names/Values for XPath generation:"))
layout.addSpacerItem(QSpacerItem(2,5, QSizePolicy.Expanding, QSizePolicy.Minimum))
tag_layout = QHBoxLayout()
# Elements
self.tag_name_label = QLabel("Tag name:")
self.tag_name_combobox = QComboBox()
self.tag_name_combobox.setEditable(True)
self.tag_name_combobox.currentTextChanged.connect(self.on_tag_name_changed)
self.tag_value_label = QLabel("Tag value:")
self.tag_value_combobox = QComboBox()
self.tag_value_combobox.setEditable(True)
# Set expanding size policy for comboboxes
self.tag_name_combobox.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
self.tag_value_combobox.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
tag_layout.addWidget(self.tag_name_label)
tag_layout.addWidget(self.tag_name_combobox)
tag_layout.addWidget(self.tag_value_label)
tag_layout.addWidget(self.tag_value_combobox)
layout.addLayout(tag_layout)
att_layout = QHBoxLayout()
# Elements
self.attribute_name_label = QLabel("Attr name:")
self.attribute_name_combobox = QComboBox()
self.attribute_name_combobox.setEditable(True)
self.attribute_name_combobox.currentTextChanged.connect(self.on_attribute_name_changed)
self.attribute_value_label = QLabel("Attr value:")
self.attribute_value_combobox = QComboBox()
self.attribute_value_combobox.setEditable(True)
att_layout.addWidget(self.attribute_name_label)
att_layout.addWidget(self.attribute_name_combobox)
att_layout.addWidget(self.attribute_value_label)
att_layout.addWidget(self.attribute_value_combobox)
layout.addLayout(att_layout)
layout.addSpacerItem(QSpacerItem(40,10, QSizePolicy.Expanding, QSizePolicy.Minimum))
# Set expanding size policy for comboboxes
self.attribute_name_combobox.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
self.attribute_value_combobox.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
function_layout = QHBoxLayout()
# Elements
self.radio_button_equals = QRadioButton("Equals")
# self.radio_button_equals.setChecked(True)
self.radio_button_contains = QRadioButton("Contains")
# self.radio_button_contains.setDisabled(True)
self.radio_button_startswith = QRadioButton("Starts-with")
# self.radio_button_startswith.setDisabled(True)
self.radio_button_greater = QRadioButton("Greater")
# self.radio_button_greater.setDisabled(True)
self.radio_button_smaller = QRadioButton("Smaller")
# self.radio_button_smaller.setDisabled(True)
function_layout.addWidget(QLabel("Function:"))
function_layout.addWidget(self.radio_button_equals)
function_layout.addWidget(self.radio_button_contains)
function_layout.addWidget(self.radio_button_startswith)
function_layout.addWidget(self.radio_button_greater)
function_layout.addWidget(self.radio_button_smaller)
layout.addLayout(function_layout)
build_xpath_layout = QHBoxLayout()
self.xpath_expression_input = QLineEdit()
self.xpath_expression_input.setPlaceholderText("Enter a XPath expression or build one...")
self.build_xpath_button = QPushButton("BUILD XPATH")
self.build_xpath_button.setToolTip("Builds XPath expression based on the selected ComboBox values for Tag Name/Value and Attribute Name/Value")
self.build_xpath_button.clicked.connect(self.build_xpath)
self.add_xpath_to_list_button = QPushButton("ADD XPATH TO LIST")
self.add_xpath_to_list_button.setToolTip("Adds currently entered XPath expression to the List below which is used to match for in the XML File(s).")
self.add_xpath_to_list_button.clicked.connect(self.add_xpath_expression_to_listbox)
self.add_xpath_to_list_button.clicked.connect(self.update_statusbar_xpath_listbox_count)
build_xpath_layout.addWidget(self.xpath_expression_input)
build_xpath_layout.addWidget(self.build_xpath_button)
layout.addLayout(build_xpath_layout)
layout.addWidget(self.add_xpath_to_list_button)
group.setLayout(layout)
return group
# ======= START FUNCTIONS FOR create_xml_eval_group ======= #
def on_tag_name_changed(self, selected_tag):
if not selected_tag:
return []
try:
attributes = self.get_attributes(self.eval_input_file, selected_tag)
self.attribute_name_combobox.clear()
self.attribute_name_combobox.addItems(attributes)
values_xml = self.get_tag_values(self.eval_input_file, selected_tag)
self.tag_value_combobox.clear()
self.tag_value_combobox.addItems(values_xml)
# Disable tag value combo box if there are no values for the selected tag
if not values_xml or all(value.strip() == "" for value in values_xml if value is not None):
self.tag_value_combobox.setDisabled(True)
self.tag_value_combobox.clear()
else:
self.tag_value_combobox.setDisabled(False)
# Disable attribute name and value combo boxes if there are no attributes for the selected tag
if not attributes:
self.attribute_name_combobox.setDisabled(True)
self.attribute_name_combobox.clear()
self.attribute_value_combobox.setDisabled(True)
self.attribute_value_combobox.clear()
else:
self.attribute_name_combobox.setDisabled(False)
except Exception as ex:
message = f"An exception of type {type(ex).__name__} occurred. Arguments: {ex.args!r}"
QMessageBox.critical(self, "An exception occurred", message)
def on_attribute_name_changed(self, selected_attribute):
try:
selected_tag = self.tag_name_combobox.currentText()
attribute_values = self.get_attribute_values(self.eval_input_file, selected_tag, selected_attribute)
self.attribute_value_combobox.clear()
self.attribute_value_combobox.addItems(attribute_values)
# Disable attribute value combo box if there are no attribute values
if not attribute_values:
self.attribute_value_combobox.setDisabled(True)
self.attribute_value_combobox.clear()
else:
self.attribute_value_combobox.setDisabled(False)
# Disable tag value combo box if the selected tag has no values
values_xml = self.get_tag_values(self.eval_input_file, selected_tag)
if not values_xml:
self.tag_value_combobox.setDisabled(True)
self.tag_value_combobox.clear()
except Exception as ex:
message = f"An exception of type {type(ex).__name__} occurred. Arguments: {ex.args!r}"
QMessageBox.critical(self,"Exception in Program", message)
def get_attributes(self, eval_input_file, selected_tag):
if not eval_input_file or not selected_tag:
return []
try:
root = ET.parse(eval_input_file).getroot()
attributes = set()
for elem in root.iter(selected_tag):
attributes.update(elem.attrib.keys())
return sorted(attributes)
except Exception as ex:
message = f"An exception of type {type(ex).__name__} occurred. Arguments: {ex.args!r}"
QMessageBox.critical(self,"Error getting attributes", message)
return []
def get_tag_values(self, eval_input_file, selected_tag):
if not eval_input_file or not selected_tag:
return []
try:
root = ET.parse(eval_input_file).getroot()
values = set()
for elem in root.iter(selected_tag):
if elem.text and elem.text.strip():
values.add(elem.text.strip())
return sorted(values)
except Exception as ex:
message = f"An exception of type {type(ex).__name__} occurred. Arguments: {ex.args!r}"
QMessageBox.critical(self,"Error getting tag values", message)
return []
def get_attribute_values(self, eval_input_file, selected_tag, selected_attribute):
if not eval_input_file or not selected_tag or not selected_attribute:
return []
try:
root = ET.parse(eval_input_file).getroot()
values = set()
for elem in root.iter(selected_tag):
if selected_attribute in elem.attrib:
values.add(elem.attrib[selected_attribute])
return sorted(values)
except Exception as ex:
message = f"An exception of type {type(ex).__name__} occurred. Arguments: {ex.args!r}"
QMessageBox.critical(self, "Error getting attribute values", message)
return []
def parse_xml(self, xml_file):
try:
self.parse_xml_thread = QThread()
self.parse_xml_worker = XMLParserThread(None, xml_file)
self.parse_xml_worker.moveToThread(self.parse_xml_thread)
# Connect signals and slots
self.parse_xml_worker.finished.connect(self.on_xml_parsed)
self.parse_xml_worker.finished.connect(self.parse_xml_thread.quit)
self.parse_xml_worker.show_error_message.connect(self.show_error_message)
self.parse_xml_thread.started.connect(self.parse_xml_worker.run)
# Start the thread
self.parse_xml_thread.start()
except Exception as ex:
message = f"An exception of type {type(ex).__name__} occurred. Arguments: {ex.args!r}"
QMessageBox.critical(self, "Exception in Program", message)
def on_xml_parsed(self, result: dict):
self.xml_output.setText(result['xml_string'])
self.tag_name_combobox.clear()
self.tag_value_combobox.clear()
self.attribute_name_combobox.clear()
self.attribute_value_combobox.clear()
self.tag_name_combobox.addItems(result['tags'])
self.tag_value_combobox.addItems(result['tag_values'])
self.attribute_name_combobox.addItems(result['attributes'])
self.attribute_value_combobox.addItems(result['attribute_values'])
# Sets the comboboxes to be empty, because on XML Read, for some reason the comboboxes always get filled with a random value
self.tag_name_combobox.setEditText("")
self.tag_value_combobox.setEditText("")
self.attribute_name_combobox.setEditText("")
self.attribute_value_combobox.setEditText("")
self.eval_input_file = self.parse_xml_worker.xml_file
self.program_output.setText("XML file loaded successfully.")
def read_xml(self):
try:
file_name, _ = QFileDialog.getOpenFileName(self, "Select XML File", "", "XML Files (*.xml)")
if file_name:
self.parse_xml(file_name)
except Exception as ex:
message = f"An exception of type {type(ex).__name__} occurred. Arguments: {ex.args!r}"
QMessageBox.critical(self, "Exception in Program", message)
def browse_folder(self):
folder = QFileDialog.getExistingDirectory(self, "Select Directory")
if folder:
self.folder_xml_input.setText(folder)
self.update_xml_file_count(folder)
def build_xpath(self):
try:
# Get values from comboboxes
tag_name = self.tag_name_combobox.currentText()
tag_value = self.tag_value_combobox.currentText()
attribute_name = self.attribute_name_combobox.currentText()
attribute_value = self.attribute_value_combobox.currentText()
# Initialize XPath expression
xpath_expression = ""
if tag_name:
xpath_expression = f"//{tag_name}"
if tag_value and not attribute_name:
# Case: Tag Name and Tag Value
xpath_expression += f"[text()='{tag_value}']"
elif attribute_name and not tag_value:
# Case: Tag Name and Attribute Name
xpath_expression += f"/@{attribute_name}"
elif attribute_name and attribute_value:
# Case: Tag Name, Attribute Name, and Attribute Value
xpath_expression += f"[@{attribute_name}='{attribute_value}']"
elif not tag_value and not attribute_name:
# Case: Only Tag Name
xpath_expression += "/text()"
# Criteria based on radio buttons
if tag_value or attribute_value:
criteria = []
selected_operation = self.get_selected_operation()
if tag_value:
criteria.append(self.build_tag_criterion(selected_operation, tag_value))
if attribute_name and attribute_value:
criteria.append(self.build_attribute_criterion(selected_operation, attribute_name, attribute_value))
if criteria:
xpath_expression = f"//{tag_name}[{' and '.join(criteria)}]"
# Update XPath expression input
self.xpath_expression_input.setText(xpath_expression)
except Exception as ex:
message = f"An exception of type {type(ex).__name__} occurred. Arguments: {ex.args!r}"
self.program_output.setText(f"Error building XPath: {message}")
def get_selected_operation(self):
if self.radio_button_equals.isChecked():
return "equals"
elif self.radio_button_contains.isChecked():
return "contains"
elif self.radio_button_startswith.isChecked():
return "startswith"
elif self.radio_button_greater.isChecked():
return "greater"
elif self.radio_button_smaller.isChecked():
return "smaller"
else:
return "equals" # Default to equals if no radio button is checked
def build_tag_criterion(self, operation, value):
if operation == "equals":
return f"text()='{value}'"
elif operation == "contains":
return f"contains(text(), '{value}')"
elif operation == "startswith":
return f"starts-with(text(), '{value}')"
elif operation == "greater":
return f"text() > {value}"
elif operation == "smaller":
return f"text() < {value}"