From df17e7d54a866afc434a2302e947a55a2948eb78 Mon Sep 17 00:00:00 2001 From: Laura Date: Sat, 24 Oct 2026 14:42:20 +0200 Subject: [PATCH] Actividad 1.12: Tratamiento ficheros XML (lectura xml y escritura en otro xml | lectura xml y escritura en un txt) --- .gitignore | 8 + info_IES.xml | 4 + informe_ciclos_IES.txt | 43 +++ modulos1_ciclo_DAM.xml | 27 ++ resumen_ciclos_IES.xml | 11 + src/application.properties | 2 + src/org/palomafp/aadd/ljl/AppPrincipal.java | 363 ++++++++++++++++++ .../aadd/ljl/config/ConfigManager.java | 36 ++ 8 files changed, 494 insertions(+) create mode 100644 .gitignore create mode 100644 info_IES.xml create mode 100644 informe_ciclos_IES.txt create mode 100644 modulos1_ciclo_DAM.xml create mode 100644 resumen_ciclos_IES.xml create mode 100644 src/application.properties create mode 100644 src/org/palomafp/aadd/ljl/AppPrincipal.java create mode 100644 src/org/palomafp/aadd/ljl/config/ConfigManager.java diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4281832 --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +# Ignorar la carpeta de compilados +bin/ +*.class + +# Ignorar archivos de configuración de Eclipse +.settings/ +.project +.classpath \ No newline at end of file diff --git a/info_IES.xml b/info_IES.xml new file mode 100644 index 0000000..a371d85 --- /dev/null +++ b/info_IES.xml @@ -0,0 +1,4 @@ + + + IES Virgen de la Paloma + diff --git a/informe_ciclos_IES.txt b/informe_ciclos_IES.txt new file mode 100644 index 0000000..0d7cfcf --- /dev/null +++ b/informe_ciclos_IES.txt @@ -0,0 +1,43 @@ +INFORME DE CICLOS FORMATIVOS +IES Virgen de la Paloma +======================================== + +Código: IFC05 +Nombre corto: DAM +Observaciones: +- Observación: revisar la distribución horaria de los módulos +- Este comentario está dentro de un ciclo, pero no es hijo directo del mismo + +---------------------------------------- + +Código: IFC06 +Nombre corto: DAW +Observaciones: +- Observación: reforzar las actividades prácticas de desarrollo backend +- Observación: comprobar la disponibilidad de empresas para la FFE + +---------------------------------------- + +Código: IFC03 +Nombre corto: ASIR +Observaciones: +- Observación: revisar los recursos disponibles para prácticas de redes + +---------------------------------------- + +Código: IFC02 +Nombre corto: SMR +Observaciones: +- Observación: actualizar el inventario de equipos informáticos + +---------------------------------------- + +Código: FB01 +Nombre corto: INFOBAS +Observaciones: +- Este ciclo requiere especial atención a las necesidades del alumnado +- Observación: coordinar las actividades prácticas con los tutores + + +======================================== +Fin del informe diff --git a/modulos1_ciclo_DAM.xml b/modulos1_ciclo_DAM.xml new file mode 100644 index 0000000..1f34fa5 --- /dev/null +++ b/modulos1_ciclo_DAM.xml @@ -0,0 +1,27 @@ + + + + DAM + Técnico Superior en Desarrollo de Aplicaciones Multiplataforma + + + Bases de datos + + + Entornos de desarrollo + + + Formación y orientación laboral + + + Lenguaje de marcas y sistemas de gestión de información + + + Programación + + + Sistemas informáticos + + + + diff --git a/resumen_ciclos_IES.xml b/resumen_ciclos_IES.xml new file mode 100644 index 0000000..b482f30 --- /dev/null +++ b/resumen_ciclos_IES.xml @@ -0,0 +1,11 @@ + + + IES Virgen de la Paloma + + DAM + DAW + ASIR + SMR + INFOBAS + + diff --git a/src/application.properties b/src/application.properties new file mode 100644 index 0000000..c801514 --- /dev/null +++ b/src/application.properties @@ -0,0 +1,2 @@ +# config/application.properties +ruta.xml=C:\\Users\\lauuj\\aadd\\fic12\\informacion-IES_v2.xml \ No newline at end of file diff --git a/src/org/palomafp/aadd/ljl/AppPrincipal.java b/src/org/palomafp/aadd/ljl/AppPrincipal.java new file mode 100644 index 0000000..8c39509 --- /dev/null +++ b/src/org/palomafp/aadd/ljl/AppPrincipal.java @@ -0,0 +1,363 @@ + +package org.palomafp.aadd.ljl; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.Scanner; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.palomafp.aadd.ljl.config.ConfigManager; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +public class AppPrincipal { + + private static final String FICHERO_INFO = "info_IES.xml"; + private static final String FICHERO_RESUMEN = "resumen_ciclos_IES.xml"; + private static final String FICHERO_MODULOS_DAM = "modulos1_ciclo_DAM.xml"; + private static final String FICHERO_INFORME = "informe_ciclos_IES.txt"; + + public static void main(String[] args) { + + AppPrincipal app = new AppPrincipal(); + + // Árbol DOM del fichero de origen (informacion-IES_v2.xml) + Document documentoDOM = app.cargarArbolDOMFicheroXML(); + + Scanner sc = new Scanner(System.in); + int opcion; + + do { + app.menu(); + opcion = sc.nextInt(); + + switch (opcion) { + case 1: + app.crearFicheroInstituto(documentoDOM); + break; + case 2: + app.crearFicheroResumenCiclos(documentoDOM); + break; + case 3: + app.crearFicheroModulosPrimerCursoDAM(documentoDOM); + break; + case 4: + app.crearInformeTxt(documentoDOM); + break; + case 5: + System.out.println("Saliendo del programa"); + break; + default: + System.out.println("Opción no válida. Inténtalo de nuevo."); + } + + } while (opcion != 5); + + sc.close(); + } + + private void menu() { + System.out.println("\n1. Crear XML con información del instituto (" + FICHERO_INFO + ")"); + System.out.println("2. Crear XML resumen de ciclos (" + FICHERO_RESUMEN + ")"); + System.out.println("3. Crear XML con módulos de 1º del ciclo DAM (" + FICHERO_MODULOS_DAM + ")"); + System.out.println("4. Crear informe txt de ciclos (" + FICHERO_INFORME + ") [opcional]"); + System.out.println("5. Salir"); + System.out.print("Elige una opción: "); + } + + // ------------------------------------------------------------------ + // OPCIÓN 1: crear un xml a partir de un xml -> ... + // ------------------------------------------------------------------ + private void crearFicheroInstituto(Document docOrigen) { + + Element oldInstituto = (Element) docOrigen.getElementsByTagName("instituto").item(0); + String oldNombre = textoHijo(oldInstituto, "nombre"); + + Document docNuevo = crearDocumentoVacio(); + if (docNuevo == null) { + return; + } + + // El elemento raíz hay que añadirlo al documento con appendChild + Element newInstituto = docNuevo.createElement("instituto"); + docNuevo.appendChild(newInstituto); + + Element newNombre = docNuevo.createElement("nombre"); + // le metemos el texto al + newNombre.setTextContent(oldNombre); + // y luego hacemos que esa etiqueta este como hija de + newInstituto.appendChild(newNombre); + + guardarDocumento(docNuevo, FICHERO_INFO); + } + + // ------------------------------------------------------------------ + // OPCIÓN 2: crear un xml a partir de un xml -> resumen de ciclos + // ..DAM.. + // ------------------------------------------------------------------ + private void crearFicheroResumenCiclos(Document docOrigen) { + + Element oldInstituto = (Element) docOrigen.getElementsByTagName("instituto").item(0); + + Document docNuevo = crearDocumentoVacio(); + if (docNuevo == null) { + return; + } + + Element newResumen = docNuevo.createElement("resumen"); + docNuevo.appendChild(newResumen); + + Element newInstituto = docNuevo.createElement("instituto"); + newInstituto.setAttribute("tipo", oldInstituto.getAttribute("tipo")); + newInstituto.setTextContent(textoHijo(oldInstituto, "nombre")); + newResumen.appendChild(newInstituto); + + Element newCiclos = docNuevo.createElement("ciclos"); + newResumen.appendChild(newCiclos); + + NodeList nodosCiclo = docOrigen.getElementsByTagName("ciclo"); + for (int i = 0; i < nodosCiclo.getLength(); i++) { + + // cogemos cada del documento antiguo + Element oldCiclo = (Element) nodosCiclo.item(i); + + Element newCiclo = docNuevo.createElement("ciclo"); + newCiclo.setAttribute("codigo", oldCiclo.getAttribute("codigo")); + newCiclo.setTextContent(textoHijo(oldCiclo, "nombre_corto")); + + // hacemos que sea hijo de + newCiclos.appendChild(newCiclo); + } + + guardarDocumento(docNuevo, FICHERO_RESUMEN); + } + + // ------------------------------------------------------------------ + // OPCIÓN 3: crear un xml a partir de un xml -> instituto + ciclo DAM + módulos del primer curso + // ------------------------------------------------------------------ + private void crearFicheroModulosPrimerCursoDAM(Document docOrigen) { + + Element oldInstituto = (Element) docOrigen.getElementsByTagName("instituto").item(0); + + Document docNuevo = crearDocumentoVacio(); + if (docNuevo == null) { + return; + } + + Element newIes = docNuevo.createElement("ies"); + // cuando es elemento hijo en vez de atributo nombre="" hay que llamar a textoHijo() + newIes.setAttribute("nombre", textoHijo(oldInstituto, "nombre")); + newIes.setAttribute("tipo", oldInstituto.getAttribute("tipo")); + docNuevo.appendChild(newIes); + + NodeList nodosCiclo = docOrigen.getElementsByTagName("ciclo"); + for (int i = 0; i < nodosCiclo.getLength(); i++) { + Element oldCiclo = (Element) nodosCiclo.item(i); + + // Solo nos interesa el ciclo cuyo nombre corto es DAM + if (!textoHijo(oldCiclo, "nombre_corto").equals("DAM")) { + continue; + } + + Element newCiclo = docNuevo.createElement("ciclo"); + newCiclo.setAttribute("codigo", oldCiclo.getAttribute("codigo")); + newCiclo.setAttribute("nivel", oldCiclo.getAttribute("nivel")); + newIes.appendChild(newCiclo); + + Element newNombreCorto = docNuevo.createElement("nombre_corto"); + newNombreCorto.setTextContent(textoHijo(oldCiclo, "nombre_corto")); + newCiclo.appendChild(newNombreCorto); + + Element newNombreLargo = docNuevo.createElement("nombre_largo"); + newNombreLargo.setTextContent(textoHijo(oldCiclo, "nombre_largo")); + newCiclo.appendChild(newNombreLargo); + + // Buscamos el curso número 1 + NodeList nodosCurso = oldCiclo.getElementsByTagName("curso"); + + for (int j = 0; j < nodosCurso.getLength(); j++) { + Element oldCurso = (Element) nodosCurso.item(j); + + if (!oldCurso.getAttribute("numero").equals("1")) { + continue; + } + + Element newCurso = docNuevo.createElement("curso"); + newCurso.setAttribute("num", "1"); + // hacemos que el sea hijo del + newCiclo.appendChild(newCurso); + + // ahora seleccionamos todos los del + NodeList nodosModulo = oldCurso.getElementsByTagName("modulo"); + for (int k = 0; k < nodosModulo.getLength(); k++) { + + Element oldModulo = (Element) nodosModulo.item(k); + + Element modulo = docNuevo.createElement("modulo"); + + modulo.setAttribute("id", oldModulo.getAttribute("id")); + modulo.setAttribute("ref", oldModulo.getAttribute("ref")); + + // va a pasar de ser un hijo en old a un atributo en el new + modulo.setAttribute("numero_horas", textoHijo(oldModulo, "numerohoras")); + newCurso.appendChild(modulo); + + // se va a seguir manteniendo como un hijo de + Element newTitulo = docNuevo.createElement("titulo"); + newTitulo.setTextContent(textoHijo(oldModulo, "titulo")); + modulo.appendChild(newTitulo); + } + } + } + + guardarDocumento(docNuevo, FICHERO_MODULOS_DAM); + } + + // ------------------------------------------------------------------ + // OPCIÓN 4 (opcional): crear un txt a partir de un xml + // ------------------------------------------------------------------ + private void crearInformeTxt(Document docOrigen) { + + Element oldInstituto = (Element) docOrigen.getElementsByTagName("instituto").item(0); + String linea = "========================================"; + String guiones = "----------------------------------------"; + + try (BufferedWriter bw = new BufferedWriter(new FileWriter(FICHERO_INFORME))) { + + // CABECERA + bw.write("INFORME DE CICLOS FORMATIVOS"); + bw.newLine(); + bw.write(textoHijo(oldInstituto, "nombre")); + bw.newLine(); + bw.write(linea); + bw.newLine(); + + + // CICLOS -> para ello recorremos el NodeList con un for() + NodeList nodosCiclo = docOrigen.getElementsByTagName("ciclo"); + + for (int i = 0; i < nodosCiclo.getLength(); i++) { + + Element oldCiclo = (Element) nodosCiclo.item(i); + + bw.newLine(); + bw.write("Código: " + oldCiclo.getAttribute("codigo")); + bw.newLine(); + bw.write("Nombre corto: " + textoHijo(oldCiclo, "nombre_corto")); + bw.newLine(); + bw.write("Observaciones:"); + bw.newLine(); + + // getChildNodes() -> solo hijos directos (no descendientes como getElementsByTagName) + NodeList hijos = oldCiclo.getChildNodes(); + + for (int j = 0; j < hijos.getLength(); j++) { + + Node hijo = hijos.item(j); + + if (hijo.getNodeType() == Node.COMMENT_NODE) { + + // trim() para quitar espacios y saltos de línea alrededor del comentario + String comentario = hijo.getNodeValue().trim(); + + if (!comentario.isEmpty()) { + bw.write("- " + comentario); + bw.newLine(); + } + } + } + + bw.newLine(); + if (i != nodosCiclo.getLength()-1) { + bw.write(guiones); + } + bw.newLine(); + } + + // PIE DE PÁGINA + bw.write(linea); + bw.newLine(); + bw.write("Fin del informe"); + bw.newLine(); + + System.out.println("Fichero " + FICHERO_INFORME + " creado correctamente."); + + } catch (IOException e) { + System.out.println("Error al escribir el informe: " + e.getMessage()); + } + } + + // ------------------------------------------------------------------ + // MÉTODOS AUXILIARES + // ------------------------------------------------------------------ + + /* Devuelve el texto (sin espacios sobrantes) del primer hijo con esa etiqueta, o "" si no existe. */ + private String textoHijo(Element padre, String etiqueta) { + NodeList nodos = padre.getElementsByTagName(etiqueta); + if (nodos.getLength() == 0) { + return ""; + } + return nodos.item(0).getTextContent().trim(); + } + + /* Crea un documento DOM vacío, listo para añadirle el elemento raíz. */ + private Document crearDocumentoVacio() { + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + return builder.newDocument(); + } catch (Exception e) { + System.out.println("Error al crear el documento: " + e.getMessage()); + return null; + } + } + + /* Serializa un árbol DOM a un fichero XML con sangrado y codificación UTF-8. */ + private void guardarDocumento(Document documento, String rutaFichero) { + try { + TransformerFactory tf = TransformerFactory.newInstance(); + Transformer transformer = tf.newTransformer(); + transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + // le indicamos el nameSpace (donde indicamos las reglas a cumplir) + transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); + + transformer.transform(new DOMSource(documento), new StreamResult(new File(rutaFichero))); + + System.out.println("Fichero " + rutaFichero + " creado correctamente."); + } catch (Exception e) { + System.out.println("Error al guardar " + rutaFichero + ": " + e.getMessage()); + } + } + + private Document cargarArbolDOMFicheroXML() { + + Document document = null; + + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + + File fichero = new File(ConfigManager.getRutaFicheroIES()); + document = builder.parse(fichero); + + document.getDocumentElement().normalize(); + + } catch (Exception e) { + e.printStackTrace(); + } + return document; + } + +} \ No newline at end of file diff --git a/src/org/palomafp/aadd/ljl/config/ConfigManager.java b/src/org/palomafp/aadd/ljl/config/ConfigManager.java new file mode 100644 index 0000000..0b6cde9 --- /dev/null +++ b/src/org/palomafp/aadd/ljl/config/ConfigManager.java @@ -0,0 +1,36 @@ +package org.palomafp.aadd.ljl.config; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +public class ConfigManager { + + private static final String RUTA_FICHERO_CONFIGURACION = "application.properties"; + private static final Properties PROPIEDADES_CONFIGURACION = new Properties(); + + // Constructor privado: de esta manera conseguimos que esta clase no se pueda instanciar. + private ConfigManager() { + } + + // Este bloque se ejecuta una sola vez, cuando se carga la clase ConfigManager + static { + try (InputStream inputStream = ConfigManager.class.getClassLoader().getResourceAsStream(RUTA_FICHERO_CONFIGURACION);) + { + + if (inputStream == null) { + throw new IOException("No se encuentra "+ RUTA_FICHERO_CONFIGURACION + " en el classpath"); + } + PROPIEDADES_CONFIGURACION.load(inputStream); + // que es loq ue tengo en las propiedades de la configuracion + System.out.println(PROPIEDADES_CONFIGURACION); + + } catch (IOException e) { + throw new RuntimeException("No se ha podido cargar el fichero de configuración", e); + } + } + + public static String getRutaFicheroIES() { + return PROPIEDADES_CONFIGURACION.getProperty("ruta.xml"); + } +}