import xml.etree.ElementTree as ET
import pandas as pd
import os
def estructura_igual(e1, e2):
if e1.tag != e2.tag or len(e1) != len(e2):
return False
return all(estructura_igual(c1, c2) for c1, c2 in zip(e1, e2))
def contenido_igual(e1, e2):
if (e1.text or '').strip() != (e2.text or '').strip():
return False
if (e1.tail or '').strip() != (e2.tail or '').strip():
return False
if e1.attrib != e2.attrib:
return False
if len(e1) != len(e2):
return False
return all(contenido_igual(c1, c2) for c1, c2 in zip(e1, e2))
It looks like you've provided a Python script for comparing two XML files and generating a comparison report in a pandas DataFrame, which is then saved to an Excel file. The script appears to be well-structured and functional for its purpose. However, I noticed a few potential issues and areas for improvement based on the code you shared. I'll address them step by step, provide a corrected and improved version of the script, and explain the changes.
Key Observations and Suggestions:
File Path Issues:
In your code, the file paths use a mix of forward slashes (/) and backslashes (\). While the r prefix (raw string) in Python handles backslashes correctly, using inconsistent separators can sometimes lead to confusion or errors in certain environments. It's better to use consistent separators for clarity and portability.
Recommendation: Use all backslashes with the r prefix or all forward slashes. I'll standardize them to use forward slashes in the improved version for better cross-platform compatibility.
Error Handling:
The script doesn't handle potential errors, such as file not found or XML parsing errors. If the files don't exist or are malformed, the script will crash with an exception. Adding try-except blocks around file parsing would make it more robust.
Recommendation: Add error handling to catch common exceptions like FileNotFoundError and ET.ParseError.
Code Reusability:
The file paths are hardcoded in the example usage. If you want to compare different files, you'd need to modify the script each time. I suggest making the comparar_xml function more flexible by allowing it to accept file paths as arguments (which it already does), and perhaps creating a wrapper function to handle multiple comparisons if needed.
Additionally, the DataFrame output could be expanded to include more details, like the full file paths or timestamps, but I'll keep it simple for now.
Whitespace Stripping:
Your contenido_igual function strips whitespace from text and tail, which is a good approach for ignoring insignificant whitespace in XML. If you want an exact comparison (including whitespace), you could remove the .strip() calls, but this might lead to false positives for minor formatting differences.
Output and Saving:
The script saves the result to "comparacionxml.xlsx". This will overwrite the file if it already exists, so be cautious. You might want to add a timestamp to the filename or handle file conflicts.
User
ahora quiero cambiar un poco
quiero que busque en una carpeta donde estaran archivos xml
asi quedaria una comparacion
NOTA BN Y CT AL FINAL
AME001011JS3202501BN vs AME001011JS3202501CT
Assistant
Entiendo tu solicitud. Quieres modificar el script para que busque archivos XML en una carpeta específica y realice comparaciones entre pares de archivos que sigan el patrón descrito: por ejemplo, comparar archivos que terminen con "BN.XML" contra sus equivalentes que terminen con "CT.XML", basándote en el nombre base común (como "AME001011JS3202501BN.XML" vs "AME001011JS3202501CT.XML").
He actualizado el script para que:
Reciba una ruta de carpeta como entrada.
Busque todos los archivos XML en esa carpeta.
Identifique pares basados en el nombre base (ignorando los sufijos "BN" y "CT" al final del nombre, antes de la extensión ".XML").
Para cada par encontrado, ejecute la comparación de estructura y contenido usando la lógica existente.
Genere un DataFrame con los resultados de todas las comparaciones y lo guarde en un archivo Excel.
Cambios principales:
Agregué una nueva función comparar_xml_en_carpeta que toma la ruta de la carpeta como parámetro.
Dentro de esta función, se listan los archivos XML, se identifican los que terminan con "BN.XML", y se busca el par correspondiente con "CT.XML" (reemplazando "BN" por "CT" en el nombre).
Solo se comparan pares válidos (es decir, si ambos archivos existen).
El DataFrame resultante acumula todas las comparaciones en una sola tabla.
Mantuve la lógica de comparación de XML sin cambios, pero agregué manejo de errores para casos donde no se encuentren pares o haya problemas con los archivos.
La salida se guarda en un archivo Excel, y se imprime un resumen en la consola.
Ejemplo de uso:
Si tienes una carpeta como 'C:/Users/C885353/Downloads/CT Y BN', el script buscará archivos como "AME001011JS3202501BN.XML" y "AME001011JS3202501CT.XML", y comparará sus estructuras y contenidos.
El DataFrame resultante tendrá columnas: "NOMBREARCHIVO" (el archivo con "BN"), "NOMBREARCHIVO2" (el archivo con "CT"), "DIFERENCIA ESTRUCTURA", y "DIFERENCIA EN CONTENIDO".
Si no se encuentran pares, el DataFrame estará vacío o mostrará un mensaje.
The column names and values are in Spanish ("SI" for yes, "NO" for no), which is fine if that's your preference, but ensure it's consistent with your needs.
Potential Improvements:
If you need to compare multiple pairs of files, you could modify the script to accept lists of files or iterate through a directory. For now, I'll stick to the single-pair comparison.
The script uses pandas and openpyxl (for Excel saving), so make sure these libraries are installed. You can install them with pip install pandas openpyxl.
Improved Version of the Script
Here's an updated version of your script with the following changes:
Standardized file paths to use forward slashes for consistency.
Added error handling for file parsing.
Made the code more robust by using os.path for path handling.
Added comments for clarity.
Kept the core logic the same but ensured the example usage works with the provided paths.
python
import xml.etree.ElementTree as ET
import pandas as pd
import os
def estructura_igual(e1, e2):
"""
Compara si la estructura (etiquetas y número de hijos) de dos elementos XML es igual.
"""
if e1.tag != e2.tag or len(e1) != len(e2):
return False
return all(estructura_igual(c1, c2) for c1, c2 in zip(e1, e2))
def contenido_igual(e1, e2):
"""
Compara si el contenido (texto, cola, atributos y contenido de hijos) de dos elementos XML es igual.
Ignora espacios en blanco insignificantes mediante .strip().
"""
if (e1.text or '').strip() != (e2.text or '').strip():
return False
if (e1.tail or '').strip() != (e2.tail or '').strip():
return False
if e1.attrib != e2.attrib:
return False
if len(e1) != len(e2):
return False
return all(contenido_igual(c1, c2) for c1, c2 in zip(e1, e2))
def comparar_xml(archivo1, archivo2):
"""
Compara dos archivos XML para verificar si su estructura y contenido son iguales.
Devuelve un DataFrame con los resultados.
Parámetros:
archivo1 (str): Ruta al primer archivo XML.
archivo2 (str): Ruta al segundo archivo XML.
Retorna:
pd.DataFrame: Un DataFrame con las columnas NOMBREARCHIVO, NOMBREARCHIVO2, DIFERENCIA ESTRUCTURA, y DIFERENCIA EN CONTENIDO.
"""
try:
# Parsear los archivos XML
tree1 = ET.parse(archivo1)
tree2 = ET.parse(archivo2)
root1 = tree1.getroot()
root2 = tree2.getroot()
# Inicializar resultados
estructura = "NO" # "SI" si la estructura es igual, "NO" si no
contenido = "NO" # "SI" si el contenido es igual, "NO" si no
# Comparar estructura
if estructura_igual(root1, root2):
estructura = "SI"
# Si la estructura es igual, comparar contenido
if contenido_igual(root1, root2):
contenido = "SI"
# Crear DataFrame con resultados
# Notar que "DIFERENCIA" se invierte: "NO" si igual, "SI" si diferente
resumen_df = pd.DataFrame([{
"NOMBREARCHIVO": os.path.basename(archivo1),
"NOMBREARCHIVO2": os.path.basename(archivo2),
"DIFERENCIA ESTRUCTURA": "NO" if estructura == "SI" else "SI",
"DIFERENCIA EN CONTENIDO": "NO" if contenido == "SI" else "SI"
}])
return resumen_df
except FileNotFoundError as e:
print(f"Error: Archivo no encontrado. Detalles: {e}")
return pd.DataFrame() # Retornar un DataFrame vacío en caso de error
except ET.ParseError as e:
print(f"Error: No se pudo parsear el archivo XML. Detalles: {e}")
return pd.DataFrame() # Retornar un DataFrame vacío en caso de error
except Exception as e:
print(f"Error inesperado: {e}")
return pd.DataFrame() # Retornar un DataFrame vacío para cualquier otro error
# Ejemplo de uso con tus rutas de archivos
# Asegúrate de que las rutas sean correctas y los archivos existan
archivo1 = 'C:/Users/C885353/Downloads/CT Y BN/AME001011JS3202501BN - copia.XML'
archivo2 = 'C:/Users/C885353/Downloads/CT Y BN/AME001011JS3202501BN.XML'
# Ejecutar la comparación
df_resultado = comparar_xml(archivo1, archivo2)
# Imprimir el DataFrame (si no hay errores)
if not df_resultado.empty:
print(df_resultado)
# Guardar en Excel
df_resultado.to_excel("comparacionxml.xlsx", index=False)
print("Resultado guardado en 'comparacionxml.xlsx'")
else:
print("No se pudo generar el DataFrame debido a un error.")
How to Use the Improved Script:
Run the Script: Copy and paste the code into a Python environment (e.g., Jupyter Notebook, PyCharm, or a standard Python script). Make sure you have the necessary libraries installed:
Install pandas and openpyxl if not already installed: pip install pandas openpyxl.
Verify File Paths: Update the archivo1 and archivo2 variables with the correct paths to your XML files. The paths in the example use forward slashes for consistency, but you can use backslashes with the r prefix if preferred (e.g., r'C:\Users\C885353\Downloads\CT Y BN\AME001011JS3202501BN - copia.XML').
Expected Output:
If the files are found and parsed successfully, the script will print a DataFrame like this (example based on your comparison):
code
NOMBREARCHIVO NOMBREARCHIVO2 DIFERENCIA ESTRUCTURA DIFERENCIA EN CONTENIDO
0 AME001011JS3202501BN - copia.XML AME001011JS3202501BN.XML SI SI
"SI" means there is a difference; "NO" means no difference.
The result is also saved to "comparacionxml.xlsx" in the current working directory.
If there's an error (e.g., file not found), it will print an error message and return an empty DataFrame.
Testing and Debugging:
If you run this and still encounter issues, check:
That the files exist at the specified paths.
That the XML files are well-formed (you can validate them using an XML validator tool).
Any permission issues with reading the files or writing the Excel file.
If you have a specific question, error message, or want to extend this script (e.g., to compare multiple files), let me know, and I can provide further assistance!
import xml.etree.ElementTree as ET
import pandas as pd
import os
def estructura_igual(e1, e2):
"""
Compara si la estructura (etiquetas y número de hijos) de dos elementos XML es igual.
"""
if e1.tag != e2.tag or len(e1) != len(e2):
return False
return all(estructura_igual(c1, c2) for c1, c2 in zip(e1, e2))
def contenido_igual(e1, e2):
"""
Compara si el contenido (texto, cola, atributos y contenido de hijos) de dos elementos XML es igual.
Ignora espacios en blanco insignificantes mediante .strip().
"""
if (e1.text or '').strip() != (e2.text or '').strip():
return False
if (e1.tail or '').strip() != (e2.tail or '').strip():
return False
if e1.attrib != e2.attrib:
return False
if len(e1) != len(e2):
return False
return all(contenido_igual(c1, c2) for c1, c2 in zip(e1, e2))
def comparar_xml(archivo1, archivo2):
"""
Compara dos archivos XML para verificar si su estructura y contenido son iguales.
Devuelve un DataFrame con los resultados para un par de archivos.
Parámetros:
archivo1 (str): Ruta al primer archivo XML.
archivo2 (str): Ruta al segundo archivo XML.
Retorna:
pd.DataFrame: Un DataFrame con las columnas NOMBREARCHIVO, NOMBREARCHIVO2, DIFERENCIA ESTRUCTURA, y DIFERENCIA EN CONTENIDO.
"""
try:
tree1 = ET.parse(archivo1)
tree2 = ET.parse(archivo2)
root1 = tree1.getroot()
root2 = tree2.getroot()
estructura = "NO"
contenido = "NO"
if estructura_igual(root1, root2):
estructura = "SI"
if contenido_igual(root1, root2):
contenido = "SI"
resumen_df = pd.DataFrame([{
"NOMBREARCHIVO": os.path.basename(archivo1),
"NOMBREARCHIVO2": os.path.basename(archivo2),
"DIFERENCIA ESTRUCTURA": "NO" if estructura == "SI" else "SI",
"DIFERENCIA EN CONTENIDO": "NO" if contenido == "SI" else "SI"
}])
return resumen_df
except FileNotFoundError as e:
print(f"Error: Archivo no encontrado. Detalles: {e}")
return pd.DataFrame() # Retornar DataFrame vacío
except ET.ParseError as e:
print(f"Error: No se pudo parsear el archivo XML. Detalles: {e}")
return pd.DataFrame() # Retornar DataFrame vacío
except Exception as e:
print(f"Error inesperado: {e}")
return pd.DataFrame() # Retornar DataFrame vacío
def comparar_xml_en_carpeta(carpeta):
"""
Busca archivos XML en una carpeta, identifica pares basados en el patrón (e.g., 'BN.XML' vs 'CT.XML'),
y compara su estructura y contenido. Guarda los resultados en un DataFrame y un archivo Excel.
Parámetros:
carpeta (str): Ruta a la carpeta que contiene los archivos XML.
Retorna:
pd.DataFrame: Un DataFrame con todas las comparaciones.
"""
try:
# Listar todos los archivos en la carpeta
archivos = [f for f in os.listdir(carpeta) if f.endswith('.XML') and os.path.isfile(os.path.join(carpeta, f))]
# Filtrar archivos que terminen con 'BN.XML' y buscar pares con 'CT.XML'
pares_encontrados = []
for archivo in archivos:
if archivo.endswith('BN.XML'):
# Extraer el nombre base (sin 'BN.XML')
nombre_base = archivo.replace('BN.XML', '')
archivo_ct = nombre_base + 'CT.XML'
# Verificar si el archivo con 'CT.XML' existe
ruta_bn = os.path.join(carpeta, archivo)
ruta_ct = os.path.join(carpeta, archivo_ct)
if os.path.exists(ruta_ct) and os.path.isfile(ruta_ct):
pares_encontrados.append((ruta_bn, ruta_ct))
# Si no se encuentran pares, informar y retornar DataFrame vacío
if not pares_encontrados:
print("No se encontraron pares de archivos que coincidan con el patrón (e.g., 'BN.XML' vs 'CT.XML').")
return pd.DataFrame()
# Realizar comparaciones para cada par y acumular en una lista de DataFrames
resultados = []
for ruta_bn, ruta_ct in pares_encontrados:
df_par = comparar_xml(ruta_bn, ruta_ct)
if not df_par.empty: # Solo agregar si no hay error
resultados.append(df_par)
# Combinar todos los DataFrames en uno solo
if resultados:
df_final = pd.concat(resultados, ignore_index=True)
else:
df_final = pd.DataFrame() # DataFrame vacío si no hay resultados válidos
# Guardar en Excel y retornar
if not df_final.empty:
df_final.to_excel("comparacion_xml_pares.xlsx", index=False)
print(f"Comparación completada. Resultados guardados en 'comparacion_xml_pares.xlsx'.")
print(df_final)
else:
print("No se pudo generar resultados válidos.")
return df_final
except Exception as e:
print(f"Error al procesar la carpeta: {e}")
return pd.DataFrame()
# Ejemplo de uso
# Proporciona la ruta a la carpeta que contiene los archivos XML
ruta_carpeta = 'C:/Users/C885353/Downloads/CT Y BN' # Ajusta esta ruta según tu caso
# Ejecutar la comparación en la carpeta
df_resultado = comparar_xml_en_carpeta(ruta_carpeta)
Explicación de los cambios:
Nueva función comparar_xml_en_carpeta:
Toma la ruta de la carpeta como argumento.
Usa os.listdir para listar archivos y filtra aquellos que terminan con .XML.
Identifica archivos que terminan con BN.XML, extrae el nombre base (eliminando BN.XML), y construye el nombre esperado para CT.XML.
Verifica si el archivo CT.XML existe en la misma carpeta.
Solo compara pares válidos para evitar errores.
Lógica de emparejamiento:
Se asume que el nombre base es el mismo antes de los sufijos "BN" y "CT". Por ejemplo:
Para "AME001011JS3202501BN.XML", se busca "AME001011JS3202501CT.XML".
Si no se encuentra un par, se ignora y se continúa con el siguiente.
Salida:
El DataFrame acumula todas las comparaciones en una sola tabla.
Se guarda en un archivo Excel llamado "comparacion_xml_pares.xlsx" (puedes cambiar el nombre si lo deseas).
Si no se encuentran pares o hay errores, se imprime un mensaje y se retorna un DataFrame vacío.
Ejemplo de salida en consola:
Si se encuentran pares, el DataFrame podría verse así:
code
NOMBREARCHIVO NOMBREARCHIVO2 DIFERENCIA ESTRUCTURA DIFERENCIA EN CONTENIDO
0 AME001011JS3202501BN.XML AME001011JS3202501CT.XML SI NO
1 OtroArchivoBN.XML OtroArchivoCT.XML NO SI
"SI" en "DIFERENCIA" significa que hay una diferencia; "NO" significa que no hay diferencia.
Requisitos y consideraciones:
Asegúrate de que la carpeta exista y contenga archivos XML con el patrón esperado.
Instala las bibliotecas necesarias si no las tienes: pip install pandas openpyxl.
Si los sufijos o el patrón cambian (e.g., no siempre es "BN" y "CT" al final), puedes ajustar la lógica en la función comparar_xml_en_carpeta.
Manejo de errores: El script maneja casos comunes como archivos no encontrados o XML mal formados.
Si necesitas más ajustes, como cambiar el patrón de emparejamiento o agregar más funcionalidades (e.g., comparar múltiples carpetas), avísame para refinarlo. ¡Prueba el script con tu carpeta y dime si funciona!