Actividad 1.12: Tratamiento ficheros XML (lectura xml y escritura en otro xml | lectura xml y escritura en un txt)

This commit is contained in:
Laura
2026-10-24 14:42:20 +02:00
commit df17e7d54a
8 changed files with 494 additions and 0 deletions
+2
View File
@@ -0,0 +1,2 @@
# config/application.properties
ruta.xml=C:\\Users\\lauuj\\aadd\\fic12\\informacion-IES_v2.xml
+363
View File
@@ -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 -> <instituto><nombre>...</nombre></instituto>
// ------------------------------------------------------------------
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 <nombre>
newNombre.setTextContent(oldNombre);
// y luego hacemos que esa etiqueta <nombre> este como hija de <instituto>
newInstituto.appendChild(newNombre);
guardarDocumento(docNuevo, FICHERO_INFO);
}
// ------------------------------------------------------------------
// OPCIÓN 2: crear un xml a partir de un xml -> resumen de ciclos
// <resumen><instituto tipo="FP">..</instituto><ciclos><ciclo codigo="..">DAM</ciclo>..
// ------------------------------------------------------------------
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 <ciclo> 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 <ciclo> sea hijo de <ciclos>
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 <nombre> 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 <curso> sea hijo del <ciclo>
newCiclo.appendChild(newCurso);
// ahora seleccionamos todos los <modulo> del <curso numero=1>
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"));
// <numero_horas> 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);
// <titulo> se va a seguir manteniendo como un hijo de <modulo>
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;
}
}
@@ -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");
}
}