private InputStream getInputStream(Source source) throws Exception { Transformer trans = TransformerFactory.newInstance().newTransformer(); ByteArrayBuffer bab = new ByteArrayBuffer(); StreamResult result = new StreamResult(bab); trans.transform(source, result); return bab.newInputStream(); }
public static String format(String xmlStr) { // Instantiate transformer input Source xmlInput = new StreamSource(new StringReader(xmlStr)); StreamResult xmlOutput = new StreamResult(new StringWriter()); // Configure transformer Transformer transformer; try { transformer = TransformerFactory.newInstance().newTransformer(); } catch (TransformerConfigurationException e) { logger.error(e.getMessage(), e); return xmlStr; } catch (TransformerFactoryConfigurationError e) { // TODO Auto-generated catch block logger.error(e.getMessage(), e); return xmlStr; } // An identity transformer try { transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.transform(xmlInput, xmlOutput); } catch (TransformerException e) { logger.error(e.getMessage(), e); return xmlStr; } return xmlOutput.getWriter().toString(); }
public void write(HttpServletResponse response) { StreamResult streamResult; SAXTransformerFactory tf; TransformerHandler hd; Transformer serializer; try { try { streamResult = new StreamResult(response.getWriter()); tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); hd = tf.newTransformerHandler(); serializer = hd.getTransformer(); serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8"); serializer.setOutputProperty( OutputKeys.DOCTYPE_SYSTEM, "http://labs.omniti.com/resmon/trunk/resources/resmon.dtd"); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); hd.setResult(streamResult); hd.startDocument(); AttributesImpl atts = new AttributesImpl(); hd.startElement("", "", "ResmonResults", atts); for (ResmonResult r : s) { r.write(hd); } hd.endElement("", "", "ResmonResults"); hd.endDocument(); } catch (TransformerConfigurationException tce) { response.getWriter().println(tce.getMessage()); } catch (SAXException se) { response.getWriter().println(se.getMessage()); } } catch (IOException ioe) { } }
private void soapMessage(String path, String wsName, String wsPortName) { try { URL wsdlURL = new URL(APP_SERVER + path); final String NS = AbstractServiceImpl.WS_TARGET_NAMESPACE; Service service = Service.create(wsdlURL, new QName(NS, wsName)); Dispatch<Source> dispatcher = service.createDispatch(new QName(NS, wsPortName), Source.class, Service.Mode.PAYLOAD); Source request = new StreamSource(new StringReader("<hello/>")); Source response = dispatcher.invoke(request); assertNotNull(response); Transformer transformer = TransformerFactory.newInstance().newTransformer(); final StringWriter writer = new StringWriter(); Result output = new StreamResult(writer); transformer.transform(response, output); Message message = new Message("clientMessages"); message.dumpFormattedMessage( EchoServiceClient.class, Message.LevelEnum.INFO, "receivedAnswer", writer.toString()); } catch (MalformedURLException e) { e.printStackTrace(); fail(String.valueOf(e)); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } }
/** * Method adds a new Spring bean definition to the XML application context file. * * @param project * @param jaxbElement */ public void addBeanDefinition(File configFile, Project project, Object jaxbElement) { Source xsltSource; Source xmlSource; try { xsltSource = new StreamSource(new ClassPathResource("transform/add-bean.xsl").getInputStream()); xsltSource.setSystemId("add-bean"); xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(configFile))); // create transformer Transformer transformer = transformerFactory.newTransformer(xsltSource); transformer.setParameter( "bean_content", getXmlContent(jaxbElement) .replaceAll("(?m)^(.)", getTabs(1, project.getSettings().getTabSize()) + "$1")); // transform StringResult result = new StringResult(); transformer.transform(xmlSource, result); FileUtils.writeToFile( format(result.toString(), project.getSettings().getTabSize()), configFile); return; } catch (IOException e) { throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e); } catch (TransformerException e) { throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e); } }
public void saveToXml(String fileName) throws ParserConfigurationException, FileNotFoundException, TransformerException, TransformerConfigurationException { System.out.println("Saving network topology to file " + fileName); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document doc = parser.newDocument(); Element root = doc.createElement("neuralNetwork"); root.setAttribute("dateOfExport", new Date().toString()); Element layers = doc.createElement("structure"); layers.setAttribute("numberOfLayers", Integer.toString(this.numberOfLayers())); for (int il = 0; il < this.numberOfLayers(); il++) { Element layer = doc.createElement("layer"); layer.setAttribute("index", Integer.toString(il)); layer.setAttribute("numberOfNeurons", Integer.toString(this.getLayer(il).numberOfNeurons())); for (int in = 0; in < this.getLayer(il).numberOfNeurons(); in++) { Element neuron = doc.createElement("neuron"); neuron.setAttribute("index", Integer.toString(in)); neuron.setAttribute( "NumberOfInputs", Integer.toString(this.getLayer(il).getNeuron(in).numberOfInputs())); neuron.setAttribute( "threshold", Double.toString(this.getLayer(il).getNeuron(in).threshold)); for (int ii = 0; ii < this.getLayer(il).getNeuron(in).numberOfInputs(); ii++) { Element input = doc.createElement("input"); input.setAttribute("index", Integer.toString(ii)); input.setAttribute( "weight", Double.toString(this.getLayer(il).getNeuron(in).getInput(ii).weight)); neuron.appendChild(input); } layer.appendChild(neuron); } layers.appendChild(layer); } root.appendChild(layers); doc.appendChild(root); // save File xmlOutputFile = new File(fileName); FileOutputStream fos; Transformer transformer; fos = new FileOutputStream(xmlOutputFile); // Use a Transformer for output TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(fos); // transform source into result will do save transformer.setOutputProperty("encoding", "iso-8859-2"); transformer.setOutputProperty("indent", "yes"); transformer.transform(source, result); }
private String importXMI(File sourceFile) throws FileNotFoundException, TransformerConfigurationException, TransformerException { BufferedReader styledata; StreamSource sourcedata; Templates stylesheet; Transformer trans; // Get the stylesheet file stream styledata = new BufferedReader( new FileReader( new File( getClass().getClassLoader().getResource("verifier/xmi2lem.xsl").getFile()))); sourcedata = new StreamSource(new FileReader(sourceFile)); // Initialize Saxon TransformerFactory factory = TransformerFactoryImpl.newInstance(); stylesheet = factory.newTemplates(new StreamSource(styledata)); // Apply the transformation trans = stylesheet.newTransformer(); StringWriter sw = new StringWriter(); trans.transform(sourcedata, new StreamResult(sw)); // return sw.toString(); return sw.getBuffer().substring(sw.getBuffer().indexOf("model")); }
/** * Transforms the given XML string using the XSL string. * * @param xmlString The String containg the XML to transform * @param xslString The XML Stylesheet String containing the transform instructions * @return String representation of the transformation */ public static String transform(String xmlString, String xslString) { String shortString = new String(xmlString); if (shortString.length() > 100) shortString = shortString.substring(0, 100) + "..."; try { TransformerFactory tFactory = TransformerFactory.newInstance(); logger.logComment("Transforming string: " + shortString); StreamSource xslFileSource = new StreamSource(new StringReader(xslString)); Transformer transformer = tFactory.newTransformer(xslFileSource); StringWriter writer = new StringWriter(); transformer.transform( new StreamSource(new StringReader(xmlString)), new StreamResult(writer)); String shortResult = writer.toString(); if (shortResult.length() > 100) shortResult = shortResult.substring(0, 100) + "..."; logger.logComment("Result: " + shortResult); return writer.toString(); } catch (TransformerException e) { GuiUtils.showErrorMessage(logger, "Error when transforming the XML: " + shortString, e, null); return null; } }
/** * Transforms the given XML file using the specified XSL file. * * @param origXmlFile The file containg the XML to transform * @param xslString The XML Stylesheet conntaining the transform instructions * @return String representation of the transformation */ public static String transform(File origXmlFile, String xslString) { if (!origXmlFile.exists()) { GuiUtils.showErrorMessage( logger, "Warning, XML file: " + origXmlFile + " doesn't exist", null, null); return null; } try { TransformerFactory tFactory = TransformerFactory.newInstance(); StreamSource xslFileSource = new StreamSource(new StringReader(xslString)); Transformer transformer = tFactory.newTransformer(xslFileSource); StringWriter writer = new StringWriter(); transformer.transform(new StreamSource(origXmlFile), new StreamResult(writer)); return writer.toString(); } catch (Exception e) { GuiUtils.showErrorMessage(logger, "Error when loading the XML file: " + origXmlFile, e, null); return null; } }
/** * Method removes a Spring bean definition from the XML application context file. Bean definition * is identified by its id or bean name. * * @param project * @param id */ public void removeBeanDefinition(File configFile, Project project, String id) { Source xsltSource; Source xmlSource; try { xsltSource = new StreamSource(new ClassPathResource("transform/delete-bean.xsl").getInputStream()); xsltSource.setSystemId("delete-bean"); List<File> configFiles = new ArrayList<>(); configFiles.add(configFile); configFiles.addAll(getConfigImports(configFile, project)); for (File file : configFiles) { xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(configFile))); // create transformer Transformer transformer = transformerFactory.newTransformer(xsltSource); transformer.setParameter("bean_id", id); // transform StringResult result = new StringResult(); transformer.transform(xmlSource, result); FileUtils.writeToFile(format(result.toString(), project.getSettings().getTabSize()), file); return; } } catch (IOException e) { throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e); } catch (TransformerException e) { throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e); } }
/** * Marshal jaxb element and try to perform basic formatting like namespace clean up and attribute * formatting with xsl transformation. * * @param jaxbElement * @return */ private String getXmlContent(Object jaxbElement) { StringResult jaxbContent = new StringResult(); springBeanMarshaller.marshal(jaxbElement, jaxbContent); Source xsltSource; try { xsltSource = new StreamSource(new ClassPathResource("transform/format-bean.xsl").getInputStream()); Transformer transformer = transformerFactory.newTransformer(xsltSource); // transform StringResult result = new StringResult(); transformer.transform(new StringSource(jaxbContent.toString()), result); if (log.isDebugEnabled()) { log.debug("Created bean definition:\n" + result.toString()); } return result.toString(); } catch (IOException e) { throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e); } catch (TransformerException e) { throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e); } }
/** * Transforms a DOM Document into a file on disk * * @param fromDocument the Document to use as the source * @param toPath the destination file path represented as a String * @throws java.io.IOException * @throws javax.xml.transform.TransformerException */ public static void transform(Document fromDocument, File toPath) throws TransformerException, IOException { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(fromDocument); StreamResult result = new StreamResult(new BufferedWriter(new FileWriter(toPath))); transformer.transform(source, result); }
private DOMSource toDOMSource(Source source) throws Exception { if (source instanceof DOMSource) { return (DOMSource) source; } Transformer trans = TransformerFactory.newInstance().newTransformer(); DOMResult result = new DOMResult(); trans.transform(source, result); return new DOMSource(result.getNode()); }
/** * Transforms a DOM Document into a String * * @param fromDocument the Document to use as the source * @return the XML as a String * @throws java.io.IOException * @throws javax.xml.transform.TransformerException */ public static String transform(Document fromDocument) throws TransformerException, IOException { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); DOMSource source = new DOMSource(fromDocument); transformer.transform(source, result); return sw.toString(); }
/** * Transforms a DOM Document into a String * * @param fromDocument the Document to use as the source * @param omitXmlDeclaration will not write the XML header if true * @return the XML as a String * @throws java.io.IOException * @throws javax.xml.transform.TransformerException */ public static String transform(Document fromDocument, boolean omitXmlDeclaration) throws TransformerException, IOException { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); if (omitXmlDeclaration) transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); StringWriter sw = new StringWriter(); transformer.transform(new DOMSource(fromDocument), new StreamResult(sw)); return sw.toString(); }
public static String transform(File fromPath) throws TransformerException, IOException { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); Reader reader = bomCheck(fromPath); StringWriter sw = new StringWriter(); transformer.transform(new StreamSource(reader), new StreamResult(sw)); return sw.toString(); }
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { DateFormat df = DateFormat.getDateTimeInstance(); String titleStr = "C3P0 Status - " + df.format(new Date()); DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance(); DocumentBuilder db = fact.newDocumentBuilder(); Document doc = db.newDocument(); Element htmlElem = doc.createElement("html"); Element headElem = doc.createElement("head"); Element titleElem = doc.createElement("title"); titleElem.appendChild(doc.createTextNode(titleStr)); Element bodyElem = doc.createElement("body"); Element h1Elem = doc.createElement("h1"); h1Elem.appendChild(doc.createTextNode(titleStr)); Element h3Elem = doc.createElement("h3"); h3Elem.appendChild(doc.createTextNode("PooledDataSources")); Element pdsDlElem = doc.createElement("dl"); pdsDlElem.setAttribute("class", "PooledDataSources"); for (Iterator ii = C3P0Registry.getPooledDataSources().iterator(); ii.hasNext(); ) { PooledDataSource pds = (PooledDataSource) ii.next(); StatusReporter sr = findStatusReporter(pds, doc); pdsDlElem.appendChild(sr.reportDtElem()); pdsDlElem.appendChild(sr.reportDdElem()); } headElem.appendChild(titleElem); htmlElem.appendChild(headElem); bodyElem.appendChild(h1Elem); bodyElem.appendChild(h3Elem); bodyElem.appendChild(pdsDlElem); htmlElem.appendChild(bodyElem); res.setContentType("application/xhtml+xml"); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); Source src = new DOMSource(doc); Result result = new StreamResult(res.getOutputStream()); transformer.transform(src, result); } catch (IOException e) { throw e; } catch (Exception e) { throw new ServletException(e); } }
private Transformer buildTransformer(String name, File xslDir, TransformerFactory tf) throws Exception { Transformer tr = tf.newTransformer( new StreamSource( new FileReader(xslDir.getAbsolutePath() + File.separatorChar + name + ".xsl"))); tr.setOutputProperty(OutputKeys.INDENT, "yes"); tr.setOutputProperty(OutputKeys.METHOD, "html"); tr.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3"); return tr; }
void outputDocument(Writer out) throws Exception { // Set up the output transformer TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); // trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); trans.setOutputProperty(OutputKeys.METHOD, "html"); // Print the DOM node StreamResult result = new StreamResult(out); DOMSource source = new DOMSource(this.document); trans.transform(source, result); }
public void write(SecureItemTable tbl, char[] password) throws IOException { OutputStream os = new FileOutputStream(file); OutputStream xmlout; if (password.length == 0) { xmlout = os; os = null; } else { PBEKeySpec keyspec = new PBEKeySpec(password); Cipher c; try { SecretKeyFactory fac = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); SecretKey key = fac.generateSecret(keyspec); c = Cipher.getInstance("PBEWithMD5AndDES"); c.init(Cipher.ENCRYPT_MODE, key, pbeSpec); } catch (java.security.GeneralSecurityException exc) { os.close(); IOException ioe = new IOException("Security exception during write"); ioe.initCause(exc); throw ioe; } CipherOutputStream out = new CipherOutputStream(os, c); xmlout = out; } try { TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); DOMSource src = new DOMSource(tbl.getDocument()); StringWriter writer = new StringWriter(); StreamResult sr = new StreamResult(writer); t.transform(src, sr); OutputStreamWriter osw = new OutputStreamWriter(xmlout, StandardCharsets.UTF_8); osw.write(writer.toString()); osw.close(); } catch (Exception exc) { IOException ioe = new IOException("Unable to serialize XML"); ioe.initCause(exc); throw ioe; } finally { xmlout.close(); if (os != null) os.close(); } tbl.setDirty(false); return; }
/** * Method updates existing Spring bean definitions in a XML application context file. Bean * definition is identified by its type defining class. * * @param project * @param type * @param jaxbElement */ public void updateBeanDefinitions( File configFile, Project project, Class<?> type, Object jaxbElement) { Source xsltSource; Source xmlSource; try { xsltSource = new StreamSource( new ClassPathResource("transform/update-bean-type.xsl").getInputStream()); xsltSource.setSystemId("update-bean"); List<File> configFiles = new ArrayList<>(); configFiles.add(configFile); configFiles.addAll(getConfigImports(configFile, project)); LSParser parser = XMLUtils.createLSParser(); GetSpringBeansFilter getBeanFilter = new GetSpringBeansFilter(type, null); parser.setFilter(getBeanFilter); for (File file : configFiles) { parser.parseURI(file.toURI().toString()); if (!CollectionUtils.isEmpty(getBeanFilter.getBeanDefinitions())) { xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(file))); String beanElement = type.getAnnotation(XmlRootElement.class).name(); String beanNamespace = type.getPackage().getAnnotation(XmlSchema.class).namespace(); // create transformer Transformer transformer = transformerFactory.newTransformer(xsltSource); transformer.setParameter("bean_element", beanElement); transformer.setParameter("bean_namespace", beanNamespace); transformer.setParameter( "bean_content", getXmlContent(jaxbElement) .replaceAll("(?m)^(\\s<)", getTabs(1, project.getSettings().getTabSize()) + "$1") .replaceAll("(?m)^(</)", getTabs(1, project.getSettings().getTabSize()) + "$1")); // transform StringResult result = new StringResult(); transformer.transform(xmlSource, result); FileUtils.writeToFile( format(result.toString(), project.getSettings().getTabSize()), file); return; } } } catch (IOException e) { throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e); } catch (TransformerException e) { throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e); } }
/** * http://www.atmarkit.co.jp/fxml/rensai2/xmltool04/02.html * * @return */ private static Transformer getTransformer() { if (s_transformer == null) { TransformerFactory transFactory = TransformerFactory.newInstance(); try { s_transformer = transFactory.newTransformer(); } catch (TransformerConfigurationException e) { } s_transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); s_transformer.setOutputProperty(OutputKeys.INDENT, "yes"); } // if return s_transformer; }
public void saveGlyphFile(OutputStream a_output) { try { Transformer transformer = getTransformer(); Document document = m_glyph.makeDocument(); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(a_output); transformer.transform(source, result); } catch (ParserConfigurationException | TransformerException e) { e.printStackTrace(); } m_savedTime = System.currentTimeMillis(); m_modifiedTime = m_savedTime; }
// This method writes a DOM document to a file public static void writeXmlFile(Document doc, File file) { try { // Prepare the DOM document for writing Source source = new DOMSource(doc); // Prepare the output file Result result = new StreamResult(file); // Write the DOM document to the file Transformer xformer = TransformerFactory.newInstance().newTransformer(); xformer.transform(source, result); } catch (TransformerException ignored) { } }
public static void main(String args[]) throws Exception { final InputStream xmlInputFile = new BufferedInputStream(new FileInputStream(args[0])); final InputStream xslFile = new BufferedInputStream(new FileInputStream(args[1])); final OutputStream xmlOutputFile = new BufferedOutputStream(new FileOutputStream(args[2])); final Transformer xslTransformer = TransformerFactory.newInstance().newTransformer(new StreamSource(xslFile)); final long startTime = System.currentTimeMillis(); xslTransformer.transform(new StreamSource(xmlInputFile), new StreamResult(xmlOutputFile)); xmlOutputFile.close(); final long endTime = System.currentTimeMillis(); System.out.println("Done in " + ((endTime - startTime) / 1000.0) + "s"); }
public void toSave() { try { TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); DOMSource source = new DOMSource(document); transformer.setOutputProperty(OutputKeys.ENCODING, "GB2312"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); PrintWriter pw = new PrintWriter(new FileOutputStream(filename)); StreamResult result = new StreamResult(pw); transformer.transform(source, result); } catch (TransformerException mye) { mye.printStackTrace(); } catch (IOException exp) { exp.printStackTrace(); } }
public static File saveToFile(String filename, Document document) throws TransformerException { // Prepare the DOM document for writing Source source = new DOMSource(document); // Prepare the output file File file = new File(filename); Result result = new StreamResult(file); // Write the DOM document to the file Transformer xformer = TransformerFactory.newInstance().newTransformer(); xformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); xformer.setOutputProperty(OutputKeys.INDENT, "yes"); xformer.transform(source, result); return file; }
private void message(String text, HttpServletResponse response, PublishAsType publishAs) { ServletOutputStream out; String xmlText; Server.logger.errorLogEntry(text); try { xmlText = "<?xml version = \"1.0\" encoding=\"utf-8\"?><request><error type=\"" + type + "\">" + "<message><version>" + Server.serverVersion + "</version><errortext>" + XMLUtil.getAsTagValue(text) + "</errortext></message></error></request>"; // System.out.println("xml text = "+xmlText); response.setHeader( "Cache-Control", "no-cache, must-revalidate, private, no-store, s-maxage=0, max-age=0"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); if (publishAs == PublishAsType.HTML) { response.setContentType("text/html;charset=utf-8"); out = response.getOutputStream(); Source xmlSource = new StreamSource(new StringReader(xmlText)); Result result = new StreamResult(out); TransformerFactory transFact = TransformerFactory.newInstance(); Transformer trans = transFact.newTransformer(xsltSource); // System.out.println(PortalEnv.appID+": xsl transformation="+PortalEnv.errorXSL); trans.transform(xmlSource, result); } else { response.setContentType("text/xml;charset=utf-8"); // response.sendError(550); out = response.getOutputStream(); out.println(xmlText); } } catch (IOException ioe) { System.out.println(ioe); ioe.printStackTrace(); } catch (TransformerConfigurationException tce) { System.out.println(tce); tce.printStackTrace(); } catch (TransformerException te) { System.out.println(te); te.printStackTrace(); } }
/** * Writes a table to a XML-file * * @param t - Output Model * @param destination - File Destination */ public static void writeXML(Model t, String destination) { try { // Create the XML document builder, and document that will be used DocumentBuilderFactory xmlBuilder = DocumentBuilderFactory.newInstance(); DocumentBuilder Builder = xmlBuilder.newDocumentBuilder(); Document xmldoc = Builder.newDocument(); // create Document node, and get it into the file Element Documentnode = xmldoc.createElement("SPREADSHEET"); xmldoc.appendChild(Documentnode); // create element nodes, and their attributes (Cells, and row/column // data) and their content for (int row = 1; row < t.getRows(); row++) { for (int col = 1; col < t.getCols(col); col++) { Element cell = xmldoc.createElement("CELL"); // set attributes cell.setAttribute("column", Integer.toString(col)); cell.setAttribute("row", Integer.toString(col)); // set content cell.appendChild(xmldoc.createTextNode((String) t.getContent(row, col))); // append node to document node Documentnode.appendChild(cell); } } // Creating a datastream for the DOM tree TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); // Indentation to make the XML file look better transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // remove the java version transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); DOMSource stream = new DOMSource(xmldoc); StreamResult target = new StreamResult(new File(destination)); // write the file transformer.transform(stream, target); } catch (ParserConfigurationException e) { System.out.println("Can't create the XML document builder"); } catch (TransformerConfigurationException e) { System.out.println("Can't create transformer"); } catch (TransformerException e) { System.out.println("Can't write to file"); } }
public synchronized void transform(File inputFile, OutputStream outputStream) throws TransformerException { ByteArrayInputStream byteArrayInputStream; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); step1.transform(new StreamSource(inputFile), new StreamResult(byteArrayOutputStream)); byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); byteArrayOutputStream = new ByteArrayOutputStream(); step2.transform( new StreamSource(byteArrayInputStream), new StreamResult(byteArrayOutputStream)); byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); step3.transform(new StreamSource(byteArrayInputStream), new StreamResult(outputStream)); }