/** * Save a single emitter to the XML file * * @param out * The location to which we should save * @param emitter * The emitter to store to the XML file * @throws IOException * Indicates a failure to write or encode the XML */ public static void saveEmitter(OutputStream out, ConfigurableEmitter emitter) throws IOException { try { DocumentBuilder builder = DocumentBuilderFactory.newInstance() .newDocumentBuilder(); Document document = builder.newDocument(); document.appendChild(emitterToElement(document, emitter)); Result result = new StreamResult(new OutputStreamWriter(out, "utf-8")); DOMSource source = new DOMSource(document); TransformerFactory factory = TransformerFactory.newInstance(); Transformer xformer = factory.newTransformer(); xformer.setOutputProperty(OutputKeys.INDENT, "yes"); xformer.transform(source, result); } catch (Exception e) { Log.error(e); throw new IOException("Failed to save emitter"); } }
public void synchroGraphicalToXml(){ Document doc=this.buildDocument(); if(doc==null)return; TransformerFactory factory=TransformerFactory.newInstance(); try{ Transformer transformer=factory.newTransformer(); transformer.setOutputProperty("encoding","utf-8"); transformer.setOutputProperty(OutputKeys.INDENT,"yes"); ByteArrayOutputStream out = new ByteArrayOutputStream(); transformer.transform(new DOMSource(doc),new StreamResult(out)); xmlEditor.getDocumentProvider().getDocument(xmlEditor.getEditorInput()).set(out.toString("utf-8")); out.close(); }catch(Exception ex){ ex.printStackTrace(); } }
/** * Test newTransformerHandler with a Template Handler along with a relative * URI in the style-sheet file. * * @throws Exception If any errors occur. */ @Test public void testcase09() throws Exception { String outputFile = USER_DIR + "saxtf009.out"; String goldFile = GOLDEN_DIR + "saxtf009GF.out"; try (FileOutputStream fos = new FileOutputStream(outputFile)) { XMLReader reader = XMLReaderFactory.createXMLReader(); SAXTransformerFactory saxTFactory = (SAXTransformerFactory)TransformerFactory.newInstance(); TemplatesHandler thandler = saxTFactory.newTemplatesHandler(); thandler.setSystemId("file:///" + XML_DIR); reader.setContentHandler(thandler); reader.parse(XSLT_INCL_FILE); TransformerHandler tfhandler= saxTFactory.newTransformerHandler(thandler.getTemplates()); Result result = new StreamResult(fos); tfhandler.setResult(result); reader.setContentHandler(tfhandler); reader.parse(XML_FILE); } assertTrue(compareWithGold(goldFile, outputFile)); }
public static void saveXMLDoctoFile(Document doc, DocumentType documentType, String path) throws TransformerException { // Save DOM XML doc to File TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); doc.setXmlVersion("1.0"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, documentType.getPublicId()); transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, documentType.getSystemId()); transformer.transform(new DOMSource(doc), new StreamResult(new File(path))); }
@Test public void test() { try { String xmlFile = "numbering63.xml"; String xslFile = "numbering63.xsl"; TransformerFactory tFactory = TransformerFactory.newInstance(); // tFactory.setAttribute("generate-translet", Boolean.TRUE); Transformer t = tFactory.newTransformer(new StreamSource(getClass().getResourceAsStream(xslFile), getClass().getResource(xslFile).toString())); StringWriter sw = new StringWriter(); t.transform(new StreamSource(getClass().getResourceAsStream(xmlFile)), new StreamResult(sw)); String s = sw.getBuffer().toString(); Assert.assertFalse(s.contains("1: Level A")); } catch (Exception e) { Assert.fail(e.getMessage()); } }
@Override public String [] getPayload (final PayloadType type, final String body) { final Source input = new StreamSource (new StringReader (body)); final StringWriter writer = new StringWriter (); final StreamResult output = new StreamResult (writer); final TransformerFactory transformerFactory = TransformerFactory.newInstance (); transformerFactory.setAttribute ("indent-number", 4); try { final Transformer transformer = transformerFactory.newTransformer (); transformer.setOutputProperty (OutputKeys.INDENT, "yes"); transformer.transform (input, output); return output.getWriter () .toString () .split ("\n"); } catch (final TransformerException e) { fail (XmlFormatTransformerError.class, "Error while Xml Transformation.", e); } return new String [] {}; }
/** * Saves the xml, contained by the specified input with the custom indentation. * If the input is the result of jaxb marshalling, make sure to set * Marshaller.JAXB_FORMATTED_OUTPUT to false in order for this method to work * properly. * * @param input * @param fos * @param indentation */ public static void saveWithCustomIndetation(ByteArrayInputStream input, FileOutputStream fos, int indentation) { try { Transformer transformer = SAXTransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(indentation)); Source xmlSource = new SAXSource(new org.xml.sax.InputSource(input)); StreamResult res = new StreamResult(fos); transformer.transform(xmlSource, res); fos.flush(); fos.close(); } catch (TransformerFactoryConfigurationError | TransformerException | IOException e) { log.log(Level.SEVERE, e.getMessage(), e); } }
protected String domSourceToString() throws SQLException { try { DOMSource source = new DOMSource(this.asDOMResult.getNode()); Transformer identity = TransformerFactory.newInstance().newTransformer(); StringWriter stringOut = new StringWriter(); Result result = new StreamResult(stringOut); identity.transform(source, result); return stringOut.toString(); } catch (Throwable t) { SQLException sqlEx = SQLError.createSQLException(t.getMessage(), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor); sqlEx.initCause(t); throw sqlEx; } }
/** * Test the simple case of including a document using xi:include within a * xi:fallback using a DocumentBuilder. * * @throws Exception If any errors occur. */ @Test(groups = {"readWriteLocalFiles"}) public void testXIncludeFallbackDOMPos() throws Exception { String resultFile = USER_DIR + "doc_fallbackDOM.out"; String goldFile = GOLDEN_DIR + "doc_fallbackGold.xml"; String xmlFile = XML_DIR + "doc_fallback.xml"; try (FileOutputStream fos = new FileOutputStream(resultFile)) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setXIncludeAware(true); dbf.setNamespaceAware(true); Document doc = dbf.newDocumentBuilder().parse(new File(xmlFile)); doc.setXmlStandalone(true); TransformerFactory.newInstance().newTransformer() .transform(new DOMSource(doc), new StreamResult(fos)); } assertTrue(compareDocumentWithGold(goldFile, resultFile)); }
public static void write(Document doc, OutputStream out) throws IOException { // XXX note that this may fail to write out namespaces correctly if the document // is created with namespaces and no explicit prefixes; however no code in // this package is likely to be doing so try { Transformer t = TransformerFactory.newInstance().newTransformer( new StreamSource(new StringReader(IDENTITY_XSLT_WITH_INDENT))); DocumentType dt = doc.getDoctype(); if (dt != null) { String pub = dt.getPublicId(); if (pub != null) { t.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, pub); } t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, dt.getSystemId()); } t.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // NOI18N Source source = new DOMSource(doc); Result result = new StreamResult(out); t.transform(source, result); } catch (Exception | TransformerFactoryConfigurationError e) { throw new IOException(e); } }
private void generateWeather(String c) throws IOException, SAXException, TransformerException, ParserConfigurationException { city = c; // creating the URL String url = "http://api.openweathermap.org/data/2.5/weather?q=" + city + "&mode=xml&appid=" + APIKey; // printing out XML URL urlString = new URL(url); URLConnection conn = urlString.openConnection(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(conn.getInputStream()); TransformerFactory transformer = TransformerFactory.newInstance(); Transformer xform = transformer.newTransformer(); xform.transform(new DOMSource(doc), new StreamResult(System.out)); }
private static void writeDocument(Document document, File resultsFile) throws TransformerException, IOException { File parentDir = resultsFile.getParentFile(); if (!parentDir.exists() && !parentDir.mkdirs()) { throw new IllegalStateException("Unable to create results directory:" + parentDir); } Transformer trans = TransformerFactory.newInstance().newTransformer(); trans.setOutputProperty(OutputKeys.METHOD, "xml"); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(resultsFile), "UTF-8"))) { trans.transform(new DOMSource(document), new StreamResult(writer)); } }
/** * SAXTFactory.newTransformerhandler() method which takes SAXSource as * argument can be set to XMLReader. SAXSource has input XML file as its * input source. XMLReader has a content handler which write out the result * to output file. Test verifies output file is same as golden file. * * @throws Exception If any errors occur. */ @Test public void testcase02() throws Exception { String outputFile = USER_DIR + "saxtf002.out"; String goldFile = GOLDEN_DIR + "saxtf002GF.out"; try (FileOutputStream fos = new FileOutputStream(outputFile); FileInputStream fis = new FileInputStream(XSLT_FILE)) { XMLReader reader = XMLReaderFactory.createXMLReader(); SAXTransformerFactory saxTFactory = (SAXTransformerFactory) TransformerFactory.newInstance(); SAXSource ss = new SAXSource(); ss.setInputSource(new InputSource(fis)); TransformerHandler handler = saxTFactory.newTransformerHandler(ss); Result result = new StreamResult(fos); handler.setResult(result); reader.setContentHandler(handler); reader.parse(XML_FILE); } assertTrue(compareWithGold(goldFile, outputFile)); }
public static boolean saveFile(Document document, File file) { boolean flag = true; try { /** 将document中的内容写入文件中 */ TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); /** 编码 */ transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(file); transformer.transform(source, result); } catch (Exception ex) { flag = false; ex.printStackTrace(); } return flag; }
@Test public void test() { try { XMLOutputFactory xof = XMLOutputFactory.newInstance(); StreamResult sr = new StreamResult(); XMLStreamWriter xsw = xof.createXMLStreamWriter(sr); NamespaceContext nc = xsw.getNamespaceContext(); System.out.println(nc.getPrefix(XMLConstants.XML_NS_URI)); System.out.println(" expected result: " + XMLConstants.XML_NS_PREFIX); System.out.println(nc.getPrefix(XMLConstants.XMLNS_ATTRIBUTE_NS_URI)); System.out.println(" expected result: " + XMLConstants.XMLNS_ATTRIBUTE); Assert.assertTrue(nc.getPrefix(XMLConstants.XML_NS_URI) == XMLConstants.XML_NS_PREFIX); Assert.assertTrue(nc.getPrefix(XMLConstants.XMLNS_ATTRIBUTE_NS_URI) == XMLConstants.XMLNS_ATTRIBUTE); } catch (Throwable ex) { Assert.fail(ex.toString()); } }
@Override public String toString() { try { TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(new StringWriter()); transformer.transform(source, result); return result.getWriter().toString(); } catch (TransformerException e) { throw new RuntimeException(e); } }
/** * Transforms the XML content to XHTML/HTML format string with the XSL. * * @param payload the XML payload to convert * @param xsltFile the XML stylesheet file * @return the transformed XHTML/HTML format string * @throws XmlException problem converting XML to HTML */ public static String xmlToHtml(String payload, File xsltFile) throws XmlException { String result = null; try { Source template = new StreamSource(xsltFile); Transformer transformer = TransformerFactory.newInstance() .newTransformer(template); Properties props = transformer.getOutputProperties(); props.setProperty(OutputKeys.OMIT_XML_DECLARATION, LOGIC_YES); transformer.setOutputProperties(props); StreamSource source = new StreamSource(new StringReader(payload)); StreamResult sr = new StreamResult(new StringWriter()); transformer.transform(source, sr); result = sr.getWriter().toString(); } catch (TransformerException e) { throw new XmlException(XmlException.XML_TRANSFORM_ERROR, e); } return result; }
@Test public void test() { try { String xmlFile = "attribset27.xml"; String xslFile = "attribset27.xsl"; TransformerFactory tFactory = TransformerFactory.newInstance(); // tFactory.setAttribute("generate-translet", Boolean.TRUE); Transformer t = tFactory.newTransformer(new StreamSource(getClass().getResourceAsStream(xslFile))); StringWriter sw = new StringWriter(); t.transform(new StreamSource(getClass().getResourceAsStream(xmlFile)), new StreamResult(sw)); String s = sw.getBuffer().toString(); Assert.assertFalse(s.contains("color") || s.contains("font-size")); } catch (Exception e) { Assert.fail(e.getMessage()); } }
/** * xml 格式化 * * @param xml * @return */ public static String xmlFormat(String xml) { if (TextUtils.isEmpty(xml)) { return "Empty/Null xml content"; } String message; try { Source xmlInput = new StreamSource(new StringReader(xml)); StreamResult xmlOutput = new StreamResult(new StringWriter()); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.transform(xmlInput, xmlOutput); message = xmlOutput.getWriter().toString().replaceFirst(">", ">\n"); } catch (TransformerException e) { message = xml; } return message; }
public static void printDocument(Node node, OutputStream out) { try { TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); transformer.transform( new DOMSource(node), new StreamResult(new OutputStreamWriter(out, "UTF-8"))); } catch (Exception e) { throw new RuntimeException(e); } }
/** * Outputs the given XML {@link Document} to the file {@code outFile}. * * TODO right now reformats the document. Needs to output as-is, respecting white-space. * * @param doc The document to output. Must not be null. * @param outFile The {@link File} where to write the document. * @param log A log in case of error. * @return True if the file was written, false in case of error. */ static boolean printXmlFile( @NonNull Document doc, @NonNull File outFile, @NonNull IMergerLog log) { // Quick thing based on comments from http://stackoverflow.com/questions/139076 try { Transformer tf = TransformerFactory.newInstance().newTransformer(); tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); //$NON-NLS-1$ tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$ tf.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$ tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", //$NON-NLS-1$ "4"); //$NON-NLS-1$ tf.transform(new DOMSource(doc), new StreamResult(outFile)); return true; } catch (TransformerException e) { log.error(Severity.ERROR, new FileAndLine(outFile.getName(), 0), "Failed to write XML file: %1$s", e.toString()); return false; } }
public static String toString(Node node, boolean pretty) { if (pretty) { trimWhiteSpace(node); } DOMSource domSource = new DOMSource(node); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); TransformerFactory tf = TransformerFactory.newInstance(); try { Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); if (pretty) { transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); } transformer.transform(domSource, result); return writer.toString(); } catch (Exception e) { throw new RuntimeException(e); } }
public void appendResults(String testName, Map<String, ? extends FormattableTable> results, Metadata metadata, int verifyCount, Document dom, OutputStream outputStream) throws TransformerException, UnsupportedEncodingException { if (dom == null) { dom = createNewDocument(metadata); } Node body = dom.getElementsByTagName("body").item(0); if (verifyCount == 1) { body.appendChild(ResultCell.createNodeWithText(dom, "h1", testName)); } if (this.htmlOptions.isDisplayAssertionSummary()) { appendAssertionSummary(testName, results, body); } for (Map.Entry<String, ? extends FormattableTable> namedTable : results.entrySet()) { appendResults(testName, namedTable.getKey(), namedTable.getValue(), body, true); } TRANSFORMER.value().transform(new DOMSource(dom), new StreamResult(new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8")))); }
/** * Writes the modified web.xml back out to war file * * @param doc * The application.xml DOM Document * @throws org.apache.tools.ant.DeployException * in case of any problems */ protected void writeWebXml(final Document doc, final OutputStream outputStream) throws DeployException { try { doc.normalize(); // Prepare the DOM document for writing DOMSource source = new DOMSource(doc); // Prepare the output file StreamResult result = new StreamResult(outputStream); // Write the DOM document to the file // Get Transformer Transformer xformer = TransformerFactory.newInstance().newTransformer(); // Write to a file xformer.transform(source, result); } catch (TransformerException tex) { throw new DeployException("Error writing out modified web xml ", tex); } }
/** * SAXTFactory.newTransformerhandler() method which takes SAXSource as * argument can be set to XMLReader. SAXSource has input XML file as its * input source. XMLReader has a transformer handler which write out the * result to output file. Test verifies output file is same as golden file. * * @throws Exception If any errors occur. */ @Test public void testcase01() throws Exception { String outputFile = USER_DIR + "saxtf001.out"; String goldFile = GOLDEN_DIR + "saxtf001GF.out"; try (FileOutputStream fos = new FileOutputStream(outputFile)) { XMLReader reader = XMLReaderFactory.createXMLReader(); SAXTransformerFactory saxTFactory = (SAXTransformerFactory) TransformerFactory.newInstance(); TransformerHandler handler = saxTFactory.newTransformerHandler(new StreamSource(XSLT_FILE)); Result result = new StreamResult(fos); handler.setResult(result); reader.setContentHandler(handler); reader.parse(XML_FILE); } assertTrue(compareWithGold(goldFile, outputFile)); }
/** * Oveloaded CustomComponent's render */ public final void render(final RenderContext ctx) { StreamSource xslSource = null; StreamSource xmlSource = null; try { xslSource = xslSource(); xmlSource = xmlSource(); final Transformer transformer = TransformerFactory.newInstance().newTransformer(xslSource); final PrintWriter pw = ctx.getWriter(); transformer.transform(xmlSource, new StreamResult(pw)); } catch (Exception e) { showUnexpectedErrorMsg(ctx, e); } finally { closeHard(xslSource); closeHard(xmlSource); } }
private static void writeOut(Document doc) throws TransformerException { TransformerFactory transformerFactory = TransformerFactory .newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.STANDALONE, "no"); DOMSource source = new DOMSource(doc); File f = new File("splFile.xml"); f.delete(); StreamResult result = new StreamResult(f); // Output to console for testing // StreamResult result = new StreamResult(System.out); transformer.transform(source, result); System.out.println("File saved!"); }
/** * Pretty print XML Node * @param node * @return * @throws XmlUtilitiesException */ public String xmlNodeToString( Node node ) throws XmlUtilitiesException { StringWriter sw = new StringWriter(); try { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputPropertiesFactory.S_KEY_INDENT_AMOUNT, "4"); transformer.setOutputProperty(OutputPropertiesFactory.S_KEY_LINE_SEPARATOR, "\n"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.transform(new DOMSource(node), new StreamResult(sw)); } catch (TransformerException te) { throw new XmlUtilitiesException("Error transforming XML node to String", te); } return sw.toString().trim(); }
public void saveInFile(Path path) throws IOException { try { Document doc = DocumentBuilderFactory.newInstance() .newDocumentBuilder() .parse(new InputSource(new StringReader(XML.toString(toJSON())))); Transformer t = TransformerFactory.newInstance().newTransformer(); t.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "yes"); t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); t.setOutputProperty(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes"); OutputStreamWriter stream = new OutputStreamWriter(new FileOutputStream(path.resolve("saved.preset").toFile()), "UTF-8"); t.transform(new DOMSource(doc), new StreamResult(stream)); } catch(Exception ex){ Main.log(ex); Main.log("Error while writing preset file"); } }
@Test public final void testXMLStackOverflowBug() throws TransformerConfigurationException, IOException, SAXException { try { SAXTransformerFactory stf = (SAXTransformerFactory) TransformerFactory.newInstance(); TransformerHandler ser = stf.newTransformerHandler(); ser.setResult(new StreamResult(System.out)); StringBuilder sb = new StringBuilder(4096); for (int x = 4096; x > 0; x--) { sb.append((char) x); } ser.characters(sb.toString().toCharArray(), 0, sb.toString().toCharArray().length); ser.endDocument(); } catch (StackOverflowError se) { se.printStackTrace(); Assert.fail("StackOverflow"); } }
/** * This test case checks for the getAssociatedStylesheet method * of TransformerFactory. * The style sheet returned is then copied to an tfactory01.out * It will then be verified to see if it matches the golden files. * * @throws Exception If any errors occur. */ @Test public void tfactory01() throws Exception { String outputFile = USER_DIR + "tfactory01.out"; String goldFile = GOLDEN_DIR + "tfactory01GF.out"; String xmlFile = XML_DIR + "TransformerFactoryTest.xml"; String xmlURI = "file:///" + XML_DIR; try (FileInputStream fis = new FileInputStream(xmlFile); FileOutputStream fos = new FileOutputStream(outputFile);) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(fis, xmlURI); DOMSource domSource = new DOMSource(doc); domSource.setSystemId(xmlURI); StreamResult streamResult = new StreamResult(fos); TransformerFactory tFactory = TransformerFactory.newInstance(); Source s = tFactory.getAssociatedStylesheet(domSource, "screen", "Modern", null); Transformer t = tFactory.newTransformer(); t.transform(s, streamResult); } assertTrue(compareWithGold(goldFile, outputFile)); }
/** * * @param file File to save Document to (ie AndroidManifest.xml) * @param doc Document being saved * @throws IOException * @throws SAXException * @throws ParserConfigurationException * @throws TransformerException */ private static void saveDocument(File file, Document doc) throws IOException, SAXException, ParserConfigurationException, TransformerException { TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.STANDALONE,"yes"); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(file); transformer.transform(source, result); }
@Test public void testStream2Stream() { try { Source input = streamUtil.prepareSource(this.getClass().getResourceAsStream(XML_FILE)); StreamResult strResult = (StreamResult) streamUtil.prepareResult(); idTransform.transform(input, strResult); streamUtil.checkResult(strResult, EXPECTED_VERSION, "UTF-8"); } catch (Exception e) { e.printStackTrace(); Assert.fail("Exception occured: " + e.getMessage()); } }
private String converteDocParaXml(Document doc) throws TransformerException { ByteArrayOutputStream os = new ByteArrayOutputStream(); Transformer trans = TransformerFactory.newInstance().newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); trans.transform(new DOMSource(doc), new StreamResult(os)); return os.toString(); }
public static void main(String[] args) throws Exception { ByteArrayOutputStream resStream = new ByteArrayOutputStream(); TransformerFactory trf = TransformerFactory.newInstance(); Transformer tr = trf.newTransformer(new StreamSource(System.getProperty("test.src", ".")+"/"+args[1])); String res, expectedRes; tr.transform( new StreamSource(System.getProperty("test.src", ".")+"/"+args[0]), new StreamResult(resStream)); res = resStream.toString(); System.out.println("Transformation completed. Result:"+res); if (!res.replaceAll("\\s","").equals(args[2])) throw new RuntimeException("Incorrect transformation result. Expected:"+args[2]+" Observed:"+res); }
@CLIOption(value="-supportedModulesXML", stop=true) public final void supportedModulesXML() throws TransformerException { Document doc = XMLUtils.docBuilder.newDocument(); Element root = XMLUtils.createRootElement(doc, "alvisnlp-supported-modules"); for (Class<? extends Module<A>> mod : moduleFactory.supportedServices()) { Element item = XMLUtils.createElement(doc, root, 1, "module-item"); item.setAttribute("target", mod.getCanonicalName()); item.setAttribute("short-target", mod.getSimpleName()); } Source source = new DOMSource(doc); Result result = new StreamResult(System.out); xmlDocTransformer.transform(source, result); }
public static String Doc2String(Document paramDocument) { try { DOMSource localDOMSource = new DOMSource(paramDocument); StringWriter localStringWriter = new StringWriter(); StreamResult localStreamResult = new StreamResult(localStringWriter); TransformerFactory localTransformerFactory = TransformerFactory.newInstance(); Transformer localTransformer = localTransformerFactory.newTransformer(); localTransformer.transform(localDOMSource, localStreamResult); return localStringWriter.toString(); } catch (Exception localException) { localException.printStackTrace(); } return null; }
/** * Transforms an XML String using a pre-compiled {@link javax.xml.transform.Transformer}. Use {@link * #getTransformer(String xslFilePath)} to produce a reusable {@link javax.xml.transform.Transformer} for a * given XSL stylesheet. To convert the resulting StringWriter to a String, call StringWriter.toString(). * * @param xmlString The XML String to transform. * @param transformer A pre-compiled {@link javax.xml.transform.Transformer} used to produce transformed * output. * @return A StringWriter containing the transformed content. */ public final static StringWriter transformStringToWriter(String xmlString, Transformer transformer) { try { StringWriter writer = new StringWriter(); StreamSource source = new StreamSource(new StringReader(xmlString)); transformer.transform(source, new StreamResult(writer)); return writer; } catch (Throwable e) { prtlnErr(e); return new StringWriter(); } }