import xmltodict import pandas as pd def save_json_to_xml(json_data, filename="DB_Structure.xml"): """ Convert JSON data to XML and save it to a file. """ xml_data = xmltodict.unparse({"root": json_data}, pretty=True) with open(filename, "w") as xml_file: xml_file.write(xml_data) print(f"XML data saved to {filename}") def save_dataframe_to_excel(df, filename="DB_Structure.xlsx"): """ Save the provided DataFrame to an Excel file. """ df.to_excel(filename, index=False) print(f"Data saved to {filename}") def save_dataframe_to_file(df, filename="DB_Structure.csv"): """ Save the provided DataFrame to a CSV file. """ df.to_csv(filename, index=False) print(f"Data saved to {filename}") def collect_data_for_table(db_struct, parent_prefix="", collected_data=[]): """ Recursively collect data from the DB structure to display in a tabular format, omitting 'fields' and 'Struct' in the names. """ is_array_element = False if isinstance(db_struct, dict): for key, value in db_struct.items(): # Skip 'fields' and 'Struct' keys in the name path # if key == "fields" or key == "Struct" or key == "Array": next_prefix = parent_prefix # Continue with the current prefix else: if isinstance(value, dict): is_array_element = value.get('is_array_element', False) if not is_array_element: next_prefix = f"{parent_prefix}.{key}" if parent_prefix else key else: next_prefix = f"{parent_prefix}{key}" if parent_prefix else key if ( isinstance(value, dict) and "type" in value ): # Directly a field with 'type' field_data = { "Nombre": next_prefix, "Tipo": value.get("type", "N/A"), "Offset": value.get("offset", "N/A"), "Dirección PLC": value.get("plc_address", "N/A"), "Comentario": value.get("comment", "N/A"), } collected_data.append(field_data) # Recursively handle nested dictionaries and lists if isinstance(value, dict) or isinstance(value, list): collect_data_for_table(value, next_prefix, collected_data) elif isinstance(db_struct, list): for index, item in enumerate(db_struct): item_prefix = f"{parent_prefix}[{index}]" if parent_prefix else f"[{index}]" collect_data_for_table(item, item_prefix, collected_data) return collected_data def display_as_table(dbs): """ Convert collected DB data into a pandas DataFrame and display it. """ all_data = [] for db_name, db_content in dbs.items(): print(f"Processing DB: {db_name}") db_data = collect_data_for_table(db_content) all_data.extend(db_data) df = pd.DataFrame(all_data) return df