Veamos con más profundidad cómo funciona el segundo paso (Crear un objeto Document que contendrá el documento XML):
01 | public void generaDocumentoXML() { |
02 | try { |
03 | // 1. Crear objeto DocumentBuilderFactory |
04 | DocumentBuilderFactory dbFactory = DocumentBuilderFactoryImpl.newInstance(); |
05 | // 2. A partir del objeto DocumentBuilderFactory crear un objeto DocumentBuilder |
06 | DocumentBuilder docBuilder = dbFactory.newDocumentBuilder(); |
07 | // 3. Generar el documento XML |
08 | documentoXML = docBuilder.newDocument(); |
09 | } catch (Exception e) { |
10 | System.out.println( "Error : " + e); |
11 | } |
12 | // 4. Crear el elemento "descargas" |
13 | descarga = documentoXML.createElement(TAG_DESCARGAS); |
14 | // 5. Agregar al documento principal |
15 | documentoXML.appendChild(descarga); |
16 | } |
- Creamos un objeto DocumentBuilderFactory, utilizando la el método newInstance() de la claseDocumentBuilderFactoryImpl.
- Creamos un objeto DocumentBuilder, con el que crearemos el objeto Document
- Generamos el documento usando el método newDocument() de DocumentBuilder
- Se crea el elemento raíz del documento XML y,
- Se añade dicho elemento al objeto Document
Después de esto, ya tenemos listo nuestro objeto Document en donde crearemos el documento XML. El paso siguiente será alimentar el documento XML con la información de nuestros objetos, lo cual se hace en el método generarDocumentoXMLDescarga:
01 | public void generarDocumentoXMLDescarga(Descargas descargas) |
02 | { |
03 | Element elemento; |
04 | Element item; |
05 | // 1. Crear elemento |
06 | elemento = documentoXML.createElement(TAG_DESCARGA); |
07 | // 2. Asignar un atributo |
08 | elemento.setAttribute(TAG_ID, "" +descargas.getID()); |
09 | // 3. Aniadir elemento al documento |
10 | descarga.appendChild(elemento); |
11 | // a. Crear item |
12 | item = documentoXML.createElement(TAG_TITULO); |
13 | // b. Asignar un dato al item |
14 | item.appendChild(documentoXML.createTextNode(descargas.getTitulo())); |
15 | // c. Aniadir el item |
16 | elemento.appendChild(item); |
17 | // todos los items se crean sigiuendo el patron a, b, c |
18 | // el código fuente completo se encuentra |
19 | //disponible para su descarga al final de este artículo |
20 | } |
- Se crea un elemento (
) - Se asigna un atributo al elemento (
) - Se añade el elemento al documento XML; posteriormente tenemos la creación de items, para dichoelemento:
a. Se crea el item ()
b. Se asigna un dato al item (datos, muchos datos )
c. Se añade el item al elemento ( )datos, muchos datos
Para generar una salida del documento XML se utilizamos el método generaTextoXML() el cual devuelve un string que contiene el documento XML:
01 | private String generaTextoXML() { |
02 | StringWriter strWriter = null ; |
03 | XMLSerializer seliarizadorXML = null ; |
04 | OutputFormat formatoSalida = null ; |
05 | try { |
06 | seliarizadorXML = new XMLSerializer(); |
07 | strWriter = new StringWriter(); |
08 | formatoSalida = new OutputFormat(); |
09 | // 1. Establecer el formato |
10 | formatoSalida.setEncoding(XML_ENCODING); |
11 | formatoSalida.setVersion(XML_VERSION); |
12 | formatoSalida.setIndenting( true ); |
13 | formatoSalida.setIndent( 4 ); |
14 | // 2. Definir un objeto donde se generara el codigo |
15 | seliarizadorXML.setOutputCharStream(strWriter); |
16 | // 3. Aplicar el formato |
17 | seliarizadorXML.setOutputFormat(formatoSalida); |
18 | // 4. Serializar documento XML |
19 | seliarizadorXML.serialize(documentoXML); |
20 | strWriter.close(); |
21 | } catch (IOException ioEx) { |
22 | System.out.println( "Error : " + ioEx); |
23 | } |
24 | return strWriter.toString(); |
25 | } |
- Utilizando un objeto de la clase OutputFormat, se asigna el tipo de codificación y versión delarchivo XML, activamos la identación y la ponemos a 4 espacios
- Un objeto XMLSerializer escribe los datos del documento XML sobre un objeto de flujo de salida, en este caso un objeto StringWriter.
- Asignamos el tipo de formato que el objeto XMLSerializer generará
- Generamos el documento XML
Comentarios
Publicar un comentario