Ejercicio 1.12
This commit is contained in:
@@ -0,0 +1,363 @@
|
||||
package org.palomafp.aadd.aez;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.util.Scanner;
|
||||
import java.io.File;
|
||||
import java.io.FileWriter;
|
||||
|
||||
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.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
import org.w3c.dom.Node;
|
||||
import org.w3c.dom.NodeList;
|
||||
|
||||
public class AppMain {
|
||||
|
||||
private static final String FICHERO_ENTRADA = "informacion-IES_v2.xml";
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Scanner sc = new Scanner(System.in);
|
||||
int opcion = -1;
|
||||
|
||||
do {
|
||||
System.out.println("\n=== ACTIVIDAD 1.12 - TRATAMIENTO XML CON DOM ===");
|
||||
System.out.println("1. Crear info_IES.xml");
|
||||
System.out.println("2. Crear resumen_ciclos_IES.xml");
|
||||
System.out.println("3. Crear modulos1_ciclo_DAM.xml");
|
||||
System.out.println("4. Generar informe_ciclos_IES.txt (Opcional)");
|
||||
System.out.println("0. Salir");
|
||||
System.out.print("Selecciona una opción: ");
|
||||
|
||||
try {
|
||||
opcion = sc.nextInt();
|
||||
switch (opcion) {
|
||||
case 1:
|
||||
crearInfoIES();
|
||||
break;
|
||||
case 2:
|
||||
crearResumenCiclos();
|
||||
break;
|
||||
case 3:
|
||||
crearModulos1DAM();
|
||||
break;
|
||||
case 4:
|
||||
generarInformeTXT();
|
||||
break;
|
||||
case 0:
|
||||
System.out.println("Saliendo del programa...");
|
||||
break;
|
||||
default:
|
||||
System.out.println("Opción no válida.");
|
||||
}
|
||||
|
||||
} catch (IOException e) {
|
||||
System.out.println(e.getMessage());
|
||||
}
|
||||
|
||||
} while (opcion != 0);
|
||||
|
||||
sc.close();
|
||||
}
|
||||
|
||||
/*
|
||||
* Opción 1: Lee el XML original y genera 'info_IES.xml' con solo la etiqueta
|
||||
* raíz <instituto> y el nombre del centro.
|
||||
*/
|
||||
private static void crearInfoIES() {
|
||||
try {
|
||||
// Carga el fichero de origen en el árbol DOM
|
||||
Document docEntrada = cargarDocumento(FICHERO_ENTRADA);
|
||||
|
||||
// Crea un nuevo documento DOM vacío en memoria para construir el nuevo XML
|
||||
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
|
||||
DocumentBuilder db = dbf.newDocumentBuilder();
|
||||
Document docSalida = db.newDocument();
|
||||
|
||||
// Extrae el texto de la etiqueta <nombre> del XML de origen
|
||||
Element rootOrig = docEntrada.getDocumentElement();
|
||||
NodeList nombreList = rootOrig.getElementsByTagName("nombre");
|
||||
String nombreTexto = "";
|
||||
if (nombreList.getLength() > 0) {
|
||||
nombreTexto = nombreList.item(0).getTextContent().trim();
|
||||
}
|
||||
|
||||
// Construye la etiqueta raíz <instituto>
|
||||
Element instituto = docSalida.createElement("instituto");
|
||||
docSalida.appendChild(instituto);
|
||||
|
||||
// Construye la etiqueta hija <nombre> y le asigna el valor extraído
|
||||
Element nombre = docSalida.createElement("nombre");
|
||||
nombre.setTextContent(nombreTexto);
|
||||
instituto.appendChild(nombre);
|
||||
|
||||
// Escribe el documento en el archivo de salida
|
||||
guardarXML(docSalida, "info_IES.xml");
|
||||
System.out.println("Fichero 'info_IES.xml' generado correctamente.");
|
||||
|
||||
} catch (Exception e) {
|
||||
System.err.println("Error al generar info_IES.xml: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Método auxiliar: Lee un fichero XML desde el sistema de archivos y construye
|
||||
* su representación en árbol DOM en memoria.
|
||||
*/
|
||||
private static Document cargarDocumento(String ruta) throws Exception {
|
||||
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
|
||||
dbf.setIgnoringElementContentWhitespace(true);
|
||||
DocumentBuilder db = dbf.newDocumentBuilder();
|
||||
Document doc = db.parse(new File(ruta));
|
||||
doc.getDocumentElement().normalize();
|
||||
|
||||
return doc;
|
||||
}
|
||||
|
||||
/*
|
||||
* Método auxiliar: Transforma la estructura DOM de memoria a un archivo físico
|
||||
* XML aplicando sangría y codificación UTF-8.
|
||||
*/
|
||||
private static void guardarXML(Document doc, String rutaSalida) throws Exception {
|
||||
TransformerFactory transformerFactory = TransformerFactory.newInstance();
|
||||
Transformer transformer = transformerFactory.newTransformer();
|
||||
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
|
||||
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
|
||||
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
|
||||
|
||||
DOMSource source = new DOMSource(doc);
|
||||
StreamResult result = new StreamResult(new File(rutaSalida));
|
||||
transformer.transform(source, result);
|
||||
}
|
||||
|
||||
/*
|
||||
* Opción 2: Lee los ciclos formativos del origen y genera
|
||||
* 'resumen_ciclos_IES.xml' con la estructura
|
||||
* <resumen><instituto>...</instituto><ciclos>...</ciclos></resumen>
|
||||
*/
|
||||
public static void crearResumenCiclos() throws Exception {
|
||||
Document docEntrada = cargarDocumento(FICHERO_ENTRADA);
|
||||
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
|
||||
DocumentBuilder db = dbf.newDocumentBuilder();
|
||||
Document docSalida = db.newDocument();
|
||||
|
||||
Element rootOrig = docEntrada.getDocumentElement();
|
||||
String tipoInstituto = rootOrig.getAttribute("tipo");
|
||||
|
||||
NodeList nombreList = rootOrig.getElementsByTagName("nombre");
|
||||
String nombreInstituto = "";
|
||||
if (nombreList.getLength() > 0) {
|
||||
nombreInstituto = nombreList.item(0).getTextContent().trim();
|
||||
}
|
||||
|
||||
// Creación del nodo raíz <resumen>
|
||||
Element resumen = docSalida.createElement("resumen");
|
||||
docSalida.appendChild(resumen);
|
||||
|
||||
// Creación del elemento <instituto tipo="...">
|
||||
Element instElem = docSalida.createElement("instituto");
|
||||
instElem.setAttribute("tipo", tipoInstituto);
|
||||
instElem.setTextContent(nombreInstituto);
|
||||
resumen.appendChild(instElem);
|
||||
|
||||
// Creación del contenedor de lista <ciclos>
|
||||
Element ciclosElem = docSalida.createElement("ciclos");
|
||||
resumen.appendChild(ciclosElem);
|
||||
|
||||
// Recorre todos los nodos <ciclo> del documento original
|
||||
NodeList ciclosList = rootOrig.getElementsByTagName("ciclo");
|
||||
for (int i = 0; i < ciclosList.getLength(); i++) {
|
||||
Element cicloOrig = (Element) ciclosList.item(i);
|
||||
String codigo = cicloOrig.getAttribute("codigo");
|
||||
|
||||
NodeList nombreCortoList = cicloOrig.getElementsByTagName("nombre_corto");
|
||||
String nombreCorto = "";
|
||||
if (nombreCortoList.getLength() > 0) {
|
||||
nombreCorto = nombreCortoList.item(0).getTextContent().trim();
|
||||
}
|
||||
|
||||
// Crea cada etiqueta <ciclo codigo="...">nombre_corto</ciclo>
|
||||
Element cicloSalida = docSalida.createElement("ciclo");
|
||||
cicloSalida.setAttribute("codigo", codigo);
|
||||
cicloSalida.setTextContent(nombreCorto);
|
||||
ciclosElem.appendChild(cicloSalida);
|
||||
}
|
||||
|
||||
guardarXML(docSalida, "resumen_ciclos_IES.xml");
|
||||
System.out.println("Fichero 'resumen_ciclos_IES.xml' generado correctamente.");
|
||||
}
|
||||
|
||||
/*
|
||||
* Opción 3: Filtra el ciclo DAM y crea 'modulos1_ciclo_DAM.xml' transformando
|
||||
* la etiqueta <numerohoras> original en un atributo 'numero_horas' del nodo
|
||||
* <modulo>.
|
||||
*/
|
||||
public static void crearModulos1DAM() throws Exception {
|
||||
Document docEntrada = cargarDocumento(FICHERO_ENTRADA);
|
||||
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
|
||||
DocumentBuilder db = dbf.newDocumentBuilder();
|
||||
Document docSalida = db.newDocument();
|
||||
|
||||
Element rootOrig = docEntrada.getDocumentElement();
|
||||
NodeList nombreList = rootOrig.getElementsByTagName("nombre");
|
||||
String nombreInstituto = "";
|
||||
if (nombreList.getLength() > 0) {
|
||||
nombreInstituto = nombreList.item(0).getTextContent().trim();
|
||||
}
|
||||
String tipoInstituto = rootOrig.getAttribute("tipo");
|
||||
|
||||
// Nodo raíz <ies nombre="..." tipo="...">
|
||||
Element iesElem = docSalida.createElement("ies");
|
||||
iesElem.setAttribute("nombre", nombreInstituto);
|
||||
iesElem.setAttribute("tipo", tipoInstituto);
|
||||
docSalida.appendChild(iesElem);
|
||||
|
||||
// Búsqueda del elemento <ciclo> cuyo <nombre_corto> es DAM
|
||||
NodeList ciclosList = rootOrig.getElementsByTagName("ciclo");
|
||||
Element cicloDAM = null;
|
||||
|
||||
for (int i = 0; i < ciclosList.getLength(); i++) {
|
||||
Element cicloElem = (Element) ciclosList.item(i);
|
||||
NodeList ncList = cicloElem.getElementsByTagName("nombre_corto");
|
||||
if (ncList.getLength() > 0 && ncList.item(0).getTextContent().trim().equalsIgnoreCase("DAM")) {
|
||||
cicloDAM = cicloElem;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (cicloDAM != null) {
|
||||
Element cicloSalida = docSalida.createElement("ciclo");
|
||||
cicloSalida.setAttribute("codigo", cicloDAM.getAttribute("codigo"));
|
||||
cicloSalida.setAttribute("nivel", cicloDAM.getAttribute("nivel"));
|
||||
iesElem.appendChild(cicloSalida);
|
||||
|
||||
String nc = cicloDAM.getElementsByTagName("nombre_corto").item(0).getTextContent().trim();
|
||||
String nl = cicloDAM.getElementsByTagName("nombre_largo").item(0).getTextContent().trim();
|
||||
|
||||
Element ncElem = docSalida.createElement("nombre_corto");
|
||||
ncElem.setTextContent(nc);
|
||||
cicloSalida.appendChild(ncElem);
|
||||
|
||||
Element nlElem = docSalida.createElement("nombre_largo");
|
||||
nlElem.setTextContent(nl);
|
||||
cicloSalida.appendChild(nlElem);
|
||||
|
||||
// Filtrado del primer curso (<curso numero="1">)
|
||||
NodeList cursosList = cicloDAM.getElementsByTagName("curso");
|
||||
for (int c = 0; c < cursosList.getLength(); c++) {
|
||||
Element cursoElem = (Element) cursosList.item(c);
|
||||
if ("1".equals(cursoElem.getAttribute("numero"))) {
|
||||
Element cursoSalida = docSalida.createElement("curso");
|
||||
cursoSalida.setAttribute("num", "1");
|
||||
cicloSalida.appendChild(cursoSalida);
|
||||
|
||||
NodeList modulosList = cursoElem.getElementsByTagName("modulo");
|
||||
for (int m = 0; m < modulosList.getLength(); m++) {
|
||||
Element modOrig = (Element) modulosList.item(m);
|
||||
String id = modOrig.getAttribute("id");
|
||||
String ref = modOrig.getAttribute("ref");
|
||||
|
||||
String numHoras = "";
|
||||
NodeList nhList = modOrig.getElementsByTagName("numerohoras");
|
||||
if (nhList.getLength() > 0) {
|
||||
numHoras = nhList.item(0).getTextContent().trim();
|
||||
}
|
||||
|
||||
String titulo = "";
|
||||
NodeList tList = modOrig.getElementsByTagName("titulo");
|
||||
if (tList.getLength() > 0) {
|
||||
titulo = tList.item(0).getTextContent().trim();
|
||||
}
|
||||
|
||||
// Creación del nuevo nodo <modulo> pasando horas como atributo
|
||||
Element modSalida = docSalida.createElement("modulo");
|
||||
modSalida.setAttribute("id", id);
|
||||
modSalida.setAttribute("ref", ref);
|
||||
modSalida.setAttribute("numero_horas", numHoras);
|
||||
|
||||
Element tituloElem = docSalida.createElement("titulo");
|
||||
tituloElem.setTextContent(titulo);
|
||||
modSalida.appendChild(tituloElem);
|
||||
|
||||
cursoSalida.appendChild(modSalida);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
guardarXML(docSalida, "modulos1_ciclo_DAM.xml");
|
||||
System.out.println("Fichero 'modulos1_ciclo_DAM.xml' generado correctamente.");
|
||||
}
|
||||
|
||||
/*
|
||||
* Opción 4: Genera un informe plano de texto (.txt) extrayendo únicamente los
|
||||
* nodos comentario (COMMENT_NODE) que sean hijos directos del nodo <ciclo>.
|
||||
*/
|
||||
private static void generarInformeTXT() {
|
||||
try {
|
||||
Document docEntrada = cargarDocumento(FICHERO_ENTRADA);
|
||||
Element rootOrig = docEntrada.getDocumentElement();
|
||||
|
||||
NodeList nombreList = rootOrig.getElementsByTagName("nombre");
|
||||
String nombreInstituto = "";
|
||||
if (nombreList.getLength() > 0) {
|
||||
nombreInstituto = nombreList.item(0).getTextContent().trim();
|
||||
}
|
||||
|
||||
File txtFile = new File("informe_ciclos_IES.txt");
|
||||
try (PrintWriter pw = new PrintWriter(new FileWriter(txtFile))) {
|
||||
pw.println("INFORME DE CICLOS FORMATIVOS");
|
||||
pw.println(nombreInstituto);
|
||||
pw.println();
|
||||
|
||||
NodeList ciclosList = rootOrig.getElementsByTagName("ciclo");
|
||||
for (int i = 0; i < ciclosList.getLength(); i++) {
|
||||
Element cicloElem = (Element) ciclosList.item(i);
|
||||
String codigo = cicloElem.getAttribute("codigo");
|
||||
|
||||
NodeList ncList = cicloElem.getElementsByTagName("nombre_corto");
|
||||
String nombreCorto = "";
|
||||
if (ncList.getLength() > 0) {
|
||||
nombreCorto = ncList.item(0).getTextContent().trim();
|
||||
}
|
||||
|
||||
pw.println("Código: " + codigo);
|
||||
pw.println("Nombre corto: " + nombreCorto);
|
||||
pw.println("Observaciones:");
|
||||
|
||||
// Obtiene todos los hijos del ciclo e identifica únicamente los comentarios
|
||||
// directos
|
||||
NodeList hijos = cicloElem.getChildNodes();
|
||||
for (int j = 0; j < hijos.getLength(); j++) {
|
||||
Node hijo = hijos.item(j);
|
||||
if (hijo.getNodeType() == Node.COMMENT_NODE) {
|
||||
String textoComentario = hijo.getNodeValue().trim();
|
||||
if (!textoComentario.isEmpty() && textoComentario.startsWith("Observación:")) {
|
||||
pw.println(textoComentario);
|
||||
} else if (!textoComentario.isEmpty()
|
||||
&& textoComentario.contains("necesidades del alumnado")) {
|
||||
pw.println(textoComentario);
|
||||
}
|
||||
}
|
||||
}
|
||||
pw.println();
|
||||
}
|
||||
|
||||
pw.println("Fin del informe");
|
||||
}
|
||||
|
||||
System.out.println("Informe 'informe_ciclos_IES.txt' generado correctamente.");
|
||||
|
||||
} catch (Exception e) {
|
||||
System.err.println("Error al generar el informe TXT: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user