List of usage examples for org.dom4j.io XMLWriter XMLWriter
public XMLWriter(OutputStream out, OutputFormat format) throws UnsupportedEncodingException
From source file:delphsim.model.Epidemia.java
License:Open Source License
/** * Guarda la informacin de esta epidemia en el archivo pasado como * parmetro, siguiendo el esquema del .xsd de la aplicacin. * @param archivoDestino El archivo destino donde se guardar el modelo. * @throws java.io.IOException Si hay problemas al escribir en disco. * @throws org.dom4j.DocumentException Si hay problemas al crear el objeto de tipo rbol. * @throws java.lang.Exception Si se produce algn otro problema. *///from www.j a v a 2 s . c om public void guardarXML(File archivoDestino) throws IOException, DocumentException, Exception { // Primero crear el documento dom4j con la informacin del modelo Document documento = DocumentHelper.createDocument(); // Elemento raz epidemia Element elementoEpidemia = new DefaultElement("epidemia"); documento.setRootElement(elementoEpidemia); elementoEpidemia.addAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); elementoEpidemia.addAttribute("xsi:noNamespaceSchemaLocation", "DelphSim1.18.xsd"); elementoEpidemia.addAttribute("unidadTiempo", this.unidadTiempo); // Elementos parmetros if (this.parametros != null) { for (Parametro param : this.parametros) { Element elementoParametro = param.volcarAXML(); elementoEpidemia.add(elementoParametro); } } // Elementos procesos if (this.procesos != null) { for (Proceso proc : this.procesos) { Element elementoProceso = proc.volcarAXML(); elementoEpidemia.add(elementoProceso); } } // Elemento poblacin Element elementoPoblacion = this.poblacion.volcarAXML(); elementoEpidemia.add(elementoPoblacion); // Elementos compartimentos for (Compartimento comp : this.compartimentos) { Element elementoCompartimento = comp.volcarAXML(); elementoEpidemia.add(elementoCompartimento); } // Luego crear el formato, stream y escritor de la salida OutputFormat formato = OutputFormat.createPrettyPrint(); formato.setEncoding("UTF-16"); formato.setIndent("\t"); formato.setNewLineAfterDeclaration(false); formato.setPadText(false); formato.setTrimText(true); formato.setXHTML(true); java.io.OutputStreamWriter salida = new java.io.OutputStreamWriter( new java.io.FileOutputStream(archivoDestino), "UTF-16"); XMLWriter escritor = new XMLWriter(salida, formato); // Y escribir escritor.write(documento); escritor.close(); }
From source file:delphsim.model.Resultado.java
License:Open Source License
/** * Mtodo esttico que exporta los valores obtenidos tras la simulacin al * formato XML./* w ww . j a va2s .c o m*/ * @param destino El archivo de destino. * @param nombres Los nombres de las distintas columnas/funciones. * @param definiciones La definicin de cada columna/funcin. * @param temps Array con los archivos temporales de los cuales obtener los * datos a exportar. * @param numPuntosTotal El nmero de puntos total que contienen los * archivos temporales. * @param numPuntosExportar El nmero de puntos que quiere obtener el usuario. * @throws java.io.IOException Si hubiera algn problema al crear el archivo en disco. */ public static void exportarComoXML(File destino, String[] nombres, String[] definiciones, File[] temps, long numPuntosTotal, long numPuntosExportar) throws IOException { // Crear el documento, el elemento 'raiz' y asignarlo org.dom4j.Document documento = DocumentHelper.createDocument(); DefaultElement elementoResultado = new DefaultElement("resultado"); documento.setRootElement(elementoResultado); // Creamos los bfers de lectura para leer los temporales BufferedReader[] buffers = new BufferedReader[temps.length]; for (int i = 0; i < temps.length; i++) { buffers[i] = new BufferedReader(new FileReader(temps[i])); } // Calculamos cada cuanto tenemos que guardar un punto double cadaCuanto; if (numPuntosTotal == numPuntosExportar) { cadaCuanto = 1.0d; } else { cadaCuanto = new Double(numPuntosTotal) / new Double(numPuntosExportar - 1); } long siguientePuntoExportar = 0; long contadorNumPuntoLeido = 0; long contadorNumPuntosExportados = 0; // Comenzamos a leer los temporales aadiendo elementos al documento String[] valores = new String[buffers.length]; for (int i = 0; i < buffers.length; i++) { valores[i] = buffers[i].readLine(); } // En el momento en que se lee un null, se termina while (valores[0] != null) { // Para cada punto que haya que exportar if (siguientePuntoExportar == contadorNumPuntoLeido) { DefaultElement nuevaFila = new DefaultElement("fila"); // Para el tiempo, nuevo elemento, su valor y aadirlo a la fila DefaultElement elementoTiempo = new DefaultElement("Tiempo"); elementoTiempo.setText(valores[0]); nuevaFila.add(elementoTiempo); // Lo mismo para cada linea, pero ademas con nombre y definicin for (int i = 1; i < valores.length; i++) { DefaultElement elementoLinea = new DefaultElement("Lnea" + i); elementoLinea.add(new DefaultAttribute("nombre", nombres[i])); elementoLinea.add(new DefaultAttribute("definicion", definiciones[i])); elementoLinea.setText(valores[i]); nuevaFila.add(elementoLinea); } // Y aadimos la nueva fila elementoResultado.add(nuevaFila); // Calculamos el siguiente punto a exportar contadorNumPuntosExportados++; siguientePuntoExportar = Math.round(cadaCuanto * contadorNumPuntosExportados); if (siguientePuntoExportar >= numPuntosTotal) { siguientePuntoExportar = numPuntosTotal - 1; } } // Leemos la siguiente lnea de los ficheros for (int i = 0; i < buffers.length; i++) { valores[i] = buffers[i].readLine(); } contadorNumPuntoLeido++; } // Cerramos los bfers y el archivo de salida for (int i = 0; i < buffers.length; i++) { buffers[i].close(); } // Imprimimos el documento como XML OutputFormat formato = OutputFormat.createPrettyPrint(); formato.setEncoding("UTF-16"); formato.setIndent("\t"); formato.setNewLineAfterDeclaration(false); formato.setPadText(false); formato.setTrimText(true); formato.setXHTML(true); OutputStreamWriter salida = new OutputStreamWriter(new FileOutputStream(destino), "UTF-16"); XMLWriter escritor = new XMLWriter(salida, formato); escritor.write(documento); escritor.flush(); escritor.close(); }
From source file:dk.netarkivet.common.utils.StreamUtils.java
License:Open Source License
/** * Write document tree to stream. Note, the stream is flushed, but not closed. * * @param doc the document tree to save. * @param os the stream to write xml to/*from www. ja v a 2s . co m*/ * @throws IOFailure On trouble writing XML to stream. */ public static void writeXmlToStream(Document doc, OutputStream os) { ArgumentNotValid.checkNotNull(doc, "Document doc"); ArgumentNotValid.checkNotNull(doc, "OutputStream os"); XMLWriter xwriter = null; try { try { OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding(UTF8_CHARSET); xwriter = new XMLWriter(os, format); xwriter.write(doc); } finally { if (xwriter != null) { xwriter.close(); } os.flush(); } } catch (IOException e) { String errMsg = "Unable to write XML to stream"; log.warn(errMsg, e); throw new IOFailure(errMsg, e); } }
From source file:dk.nsi.stamdata.replication.tools.SchemaGenerator.java
License:Mozilla Public License
public static void generate(Class<? extends View> entity, Writer writer) throws IOException { Document doc = DocumentFactory.getInstance().createDocument(); String targetNamespace = entity.getPackage().getAnnotation(XmlSchema.class).namespace(); String entityName = entity.getSimpleName().toLowerCase(); Element all = generate(doc, targetNamespace, entityName); for (Field method : entity.getDeclaredFields()) { if (method.isAnnotationPresent(XmlTransient.class)) continue; String name = method.getName(); String type = convert2SchemaType(method); addElement(all, name, type, null); }/* w ww . j a va2 s.c om*/ XMLWriter xmlWriter = new XMLWriter(writer, OutputFormat.createPrettyPrint()); xmlWriter.write(doc); }
From source file:dk.nsi.stamdata.replication.tools.SchemaGenerator.java
License:Mozilla Public License
public static void generate(RecordSpecification specification, Writer writer, String register) throws IOException { Document doc = DocumentFactory.getInstance().createDocument(); // FIXME: Register added to record spec. String namespace = Namespace.STAMDATA_3_0 + "/" + register; String entityName = specification.getTable().toLowerCase(); Element all = generate(doc, namespace, entityName); for (RecordSpecification.FieldSpecification field : specification.getFieldSpecs()) { addElement(all, field.name, convert2XsdType(field.type), field.length); }/*from www . j a v a2 s .c om*/ all.addElement("xs:element").addAttribute("name", "validFrom").addAttribute("type", "xs:dateTime"); all.addElement("xs:element").addAttribute("name", "validTo").addAttribute("type", "xs:dateTime"); XMLWriter xmlWriter = new XMLWriter(writer, OutputFormat.createPrettyPrint()); xmlWriter.write(doc); }
From source file:dom4j.Dom4JExample.java
public void write(Document document) throws IOException { // lets write to a file XMLWriter writer;/*from w w w.j a v a 2 s . c o m*/ // = new XMLWriter( // new BufferedOutputStream(outputStream)); // writer.write( document ); // writer.close(); // Pretty print the document to System.out System.out.println("\n\nPretty format"); OutputFormat format = OutputFormat.createPrettyPrint(); writer = new XMLWriter(System.out, format); writer.write(document); // Compact format to System.out System.out.println("\n\nCompact format"); format = OutputFormat.createCompactFormat(); writer = new XMLWriter(System.out, format); writer.write(document); }
From source file:edu.ccut.saturn.manager.dict.core.dbmanager.Dom4jUtils.java
License:Apache License
public static String writeXml(String file, Document doc) { String message = null;/*from w w w .ja v a 2s . c om*/ XMLWriter writer = null; OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("GB2312"); format.setIndent(true); format.setIndent(" "); format.setNewlines(true); OutputStream out = null; try { out = new FileOutputStream(file); } catch (FileNotFoundException e1) { try { String path = Thread.currentThread().getContextClassLoader().getResource(BLANK_STRING).getFile() + file.substring(1); out = new FileOutputStream(path); } catch (FileNotFoundException e) { e.printStackTrace(); } } try { writer = new XMLWriter(out, format); writer.write(doc); } catch (Exception e) { e.printStackTrace(); } finally { try { writer.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } message = TRUE; return message; }
From source file:edu.internet2.middleware.grouperClientExt.com.thoughtworks.xstream.io.xml.Dom4JDriver.java
License:Open Source License
public HierarchicalStreamWriter createWriter(final Writer out) { final HierarchicalStreamWriter[] writer = new HierarchicalStreamWriter[1]; final FilterWriter filter = new FilterWriter(out) { public void close() { writer[0].close();/*ww w .j a va 2 s .com*/ } }; writer[0] = new Dom4JXmlWriter(new XMLWriter(filter, outputFormat), xmlFriendlyReplacer()); return writer[0]; }
From source file:edu.ku.brc.dbsupport.ImportExportDB.java
License:Open Source License
/** * print all the records of a table. * @param dbTable the class name of the table *//*from w ww .j a v a2s. c om*/ @SuppressWarnings("unchecked") public void printXML(String dbTable) { Session dom4jSession = session.getSession(EntityMode.DOM4J); String query = "from " + dbTable; //$NON-NLS-1$ List userXML = dom4jSession.createQuery(query).list(); try { OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(System.out, format); for (int i = 0; i < userXML.size(); i++) { Element writeMe = (Element) userXML.get(i); writer.write(writeMe); } } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ImportExportDB.class, ex); ex.printStackTrace(); } System.out.println(); }
From source file:edu.ku.brc.dbsupport.ImportExportDB.java
License:Open Source License
/** * print a single record// w w w. j ava2 s . c o m * @param dbTable the class name of the table * @param id the id number of the record */ @SuppressWarnings("unchecked") public void printSingleRecordXML(String dbTable, int id) { Session dom4jSession = session.getSession(EntityMode.DOM4J); // load the object by using its primary key DBTableInfo info = DBTableIdMgr.getInstance().getInfoByTableName(dbTable.toLowerCase()); String primaryKey = info.getPrimaryKeyName(); String query = "from " + dbTable + " where " + primaryKey + " = " + id; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ List userXML = dom4jSession.createQuery(query).list(); try { OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(System.out, format); for (int i = 0; i < userXML.size(); i++) { Element writeMe = (Element) userXML.get(i); writer.write(writeMe); } } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ImportExportDB.class, ex); ex.printStackTrace(); } System.out.println(); }