questo codice funziona ma nei tag multipli del file xml importa solo il secondo tag,…
- User
questo codice funziona ma nei tag multipli del file xml importa solo il secondo tag, invece di tutti, lo correggi:
import xml.etree.ElementTree as ET import pyodbc import os import time
Configurazione di connessione al database
DB_PATH = r'C:\Users\Utente\Desktop\PYTHON\Fatturazione.accdb' XML_FOLDER_PATH = r'C:\Users\Utente\Desktop\PYTHON\Fattura'
Parametri per la connessione con il database MS Access
CONNECTION_STRING = ( r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};' r'DBQ=' + DB_PATH + ';' )
Connetti al database
def connect_to_db(conn_str): cnxn = pyodbc.connect(conn_str) cursor = cnxn.cursor() return cnxn, cursor
Estrai le specifiche dalla tabella Tabelle_campi
def get_table_mappings(cursor): cursor.execute(""" SELECT nodo, campo, tabella, tipo_access, lung_stringa_min, lung_stringa_max FROM Tabelle_campi WHERE nodo IS NOT NULL AND campo IS NOT NULL AND tabella IS NOT NULL """) return {row.nodo: row for row in cursor.fetchall()}
Inserisci i dati nel database
def insert_data(cursor, table_name, row_data, unix_date): columns = ', '.join(row_data.keys()) placeholders = ', '.join(['?'] * len(row_data)) values = list(row_data.values()) + [unix_date]
sql = f"INSERT INTO {table_name} ({columns}, id_doc) VALUES ({placeholders}, ?)" cursor.execute(sql, values)def parse_xml_and_insert(xml_file_path, mappings, cursor): tree = ET.parse(xml_file_path) root = tree.getroot() unix_date = int(time.time())
# Dizionario per raccogliere tutti i dati da inserire per ogni tabella inserts = {} for xml_path, spec in mappings.items(): for elem in root.findall(xml_path): text = elem.text if elem.text is not None else '' if spec.lung_stringa_min <= len(text) <= spec.lung_stringa_max: row_data = inserts.setdefault(spec.tabella, {}) row_data[spec.campo] = text # Inserisci i dati per ogni tabella for table_name, row_data in inserts.items(): insert_data(cursor, table_name, row_data, unix_date) # Assicurati di fare commit al database per salvare le modifiche cursor.commit()Funzione principale per eseguire lo script
def main(): cnxn, cursor = connect_to_db(CONNECTION_STRING) try: mappings = get_table_mappings(cursor)
for filename in os.listdir(XML_FOLDER_PATH): if filename.lower().endswith('.xml'): xml_file_path = os.path.join(XML_FOLDER_PATH, filename) parse_xml_and_insert(xml_file_path, mappings, cursor) finally: cursor.close() cnxn.close()if name == "main": main()
- Assistant
- User
- Assistant
- User
il risultato non cambia
- Assistant
- User
non funziona i record devono essere aggiunti nella tabella per riga, quindi se si tratta di tag multipli si devono aggiungere x righi per tutti i tag appartenente allo stesso rigo
- Assistant