List of usage examples for javax.xml.transform TransformerFactory newTransformer
public abstract Transformer newTransformer() throws TransformerConfigurationException;
From source file:Main.java
/** * Convert Properties to string// www. jav a2s.c o m * * @param props * @return xml string * @throws IOException */ public static String writePropToString(Properties props) throws IOException { try { org.w3c.dom.Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); org.w3c.dom.Element conf = doc.createElement("configuration"); doc.appendChild(conf); conf.appendChild(doc.createTextNode("\n")); for (Enumeration e = props.keys(); e.hasMoreElements();) { String name = (String) e.nextElement(); Object object = props.get(name); String value; if (object instanceof String) { value = (String) object; } else { continue; } org.w3c.dom.Element propNode = doc.createElement("property"); conf.appendChild(propNode); org.w3c.dom.Element nameNode = doc.createElement("name"); nameNode.appendChild(doc.createTextNode(name.trim())); propNode.appendChild(nameNode); org.w3c.dom.Element valueNode = doc.createElement("value"); valueNode.appendChild(doc.createTextNode(value.trim())); propNode.appendChild(valueNode); conf.appendChild(doc.createTextNode("\n")); } Source source = new DOMSource(doc); StringWriter stringWriter = new StringWriter(); Result result = new StreamResult(stringWriter); TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); transformer.transform(source, result); return stringWriter.getBuffer().toString(); } catch (Exception e) { throw new IOException(e); } }
From source file:Main.java
/** * Saves a DOM to a human-readable XML file (4-space indentation, UTF-8). * <p>/* w w w.ja v a2 s .co m*/ * Contains workaround for various JVM bugs. * * @param document * The DOM * @param file * The target XML file * @throws TransformerFactoryConfigurationError * In case of an XML transformation factory configuration error * @throws TransformerException * In case of an XML transformation error * @throws IOException * In case of an I/O error */ public static void saveHumanReadable(Document document, File file) throws TransformerFactoryConfigurationError, TransformerException, IOException { // Various indentation and UTF8 encoding bugs are worked around here TransformerFactory factory = TransformerFactory.newInstance(); factory.setAttribute("indent-number", new Integer(4)); Transformer transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), "UTF8"); transformer.transform(new DOMSource(document), new StreamResult(writer)); writer.close(); }
From source file:Main.java
/** * /*www . jav a2 s . c o m*/ * @param xml * @param indent * @return pretty formatted xml */ public static String prettyFormat(String xml, int indent) { try { Source xmlInput = new StreamSource(new StringReader(xml)); StringWriter stringWriter = new StringWriter(); StreamResult xmlOutput = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", indent); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(xmlInput, xmlOutput); return xmlOutput.getWriter().toString(); } catch (Exception e) { throw new RuntimeException(e); // simple exception handling, please review it } }
From source file:Main.java
public static byte[] serializeToByteArray(Document doc) throws IOException { TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = null; try {//from w ww . jav a2 s.c o m transformer = tFactory.newTransformer(); } catch (TransformerConfigurationException e) { throw new IOException("Unable to serialize XML document"); } transformer.setOutputProperty(OutputKeys.INDENT, "no"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); String encoding = doc.getInputEncoding(); if (encoding == null) encoding = "UTF-8"; transformer.setOutputProperty(OutputKeys.ENCODING, encoding); DOMSource source = new DOMSource(doc); ByteArrayOutputStream out = new ByteArrayOutputStream(); Result result = new StreamResult(out); try { transformer.transform(source, result); } catch (TransformerException e) { throw new IOException("Unable to serialize XML document"); } return out.toByteArray(); }
From source file:Main.java
public static String getStringFromXmlDoc(org.w3c.dom.Node node) throws Exception { TransformerFactory tf = TransformerFactory .newInstance("com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl", null); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(node), new StreamResult(writer)); return writer.getBuffer().toString().replaceAll("\n|\r", ""); }
From source file:Main.java
public static void vectorToXML222(String xmlFile, String xpath, String parentNodeName, Vector<HashMap> vector) { File file = new File(xmlFile); try {/* w w w.ja v a2s .co m*/ DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document; Element rootNode; if (file.exists()) { document = documentBuilder.parse(new File(xmlFile)); rootNode = document.getDocumentElement(); } else { document = documentBuilder.newDocument(); rootNode = document.createElement(xpath); document.appendChild(rootNode); } for (int x = 0; x < vector.size(); x++) { Element parentNode = document.createElement(parentNodeName); rootNode.appendChild(parentNode); HashMap hashmap = vector.get(x); Set set = hashmap.entrySet(); Iterator i = set.iterator(); while (i.hasNext()) { Map.Entry me = (Map.Entry) i.next(); // System.out.println("key=" + // me.getKey().toString()); Element em = document.createElement(me.getKey().toString()); em.appendChild(document.createTextNode(me.getValue().toString())); parentNode.appendChild(em); // System.out.println("write " + // me.getKey().toString() + // "=" // + me.getValue().toString()); } } TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(document); FileOutputStream fo = new FileOutputStream(xmlFile); StreamResult result = new StreamResult(fo); transformer.transform(source, result); } catch (Exception ex) { file.delete(); ex.printStackTrace(); } }
From source file:Main.java
public static String prettyFormat(String input, int indent, boolean isOmitXmlDeclaration) { try {/*from w w w . j av a 2s .co m*/ Source xmlInput = new StreamSource(new StringReader(input)); StringWriter stringWriter = new StringWriter(); StreamResult xmlOutput = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", indent); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); if (isOmitXmlDeclaration) { transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); } transformer.transform(xmlInput, xmlOutput); return xmlOutput.getWriter().toString(); } catch (Exception e) { throw new RuntimeException(e); // simple exception handling, please review it } }
From source file:Main.java
/** * Saves a WC3 DOM by writing it to an XML document. * * @param doc The WC3 DOM document object. * @param docPath The full path to the XML document. * @param encoding Encoding scheme to use for the XML document, e.g., * "UTF-8."//from w ww .j a va2 s.c o m * @throws TransformerConfigurationException * @throws FileNotFoundException * @throws UnsupportedEncodingException * @throws TransformerException * @throws IOException */ public static void saveDocument(final Document doc, String encoding, String docPath) throws TransformerConfigurationException, FileNotFoundException, UnsupportedEncodingException, TransformerException, IOException { TransformerFactory xf = TransformerFactory.newInstance(); xf.setAttribute("indent-number", 1); //NON-NLS Transformer xformer = xf.newTransformer(); xformer.setOutputProperty(OutputKeys.METHOD, "xml"); //NON-NLS xformer.setOutputProperty(OutputKeys.INDENT, "yes"); //NON-NLS xformer.setOutputProperty(OutputKeys.ENCODING, encoding); xformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); //NON-NLS xformer.setOutputProperty(OutputKeys.VERSION, "1.0"); File file = new File(docPath); try (FileOutputStream stream = new FileOutputStream(file)) { Result out = new StreamResult(new OutputStreamWriter(stream, encoding)); xformer.transform(new DOMSource(doc), out); stream.flush(); } }
From source file:net.sf.mcf2pdf.mcfelements.util.PdfUtil.java
/** * Converts an FO file to a PDF file using Apache FOP. * * @param fo the FO file/*from w ww . ja v a2s . c o m*/ * @param pdf the target PDF file * @param dpi the DPI resolution to use for bitmaps in the PDF * @throws IOException In case of an I/O problem * @throws FOPException In case of a FOP problem * @throws TransformerException In case of XML transformer problem */ @SuppressWarnings("rawtypes") public static void convertFO2PDF(InputStream fo, OutputStream pdf, int dpi) throws IOException, FOPException, TransformerException { FopFactory fopFactory = FopFactory.newInstance(); FOUserAgent foUserAgent = fopFactory.newFOUserAgent(); // configure foUserAgent as desired foUserAgent.setTargetResolution(dpi); // Setup output stream. Note: Using BufferedOutputStream // for performance reasons (helpful with FileOutputStreams). OutputStream out = new BufferedOutputStream(pdf); // Construct fop with desired output format Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out); // Setup JAXP using identity transformer TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); // identity // transformer // Setup input stream Source src = new StreamSource(fo); // Resulting SAX events (the generated FO) must be piped through to FOP Result res = new SAXResult(fop.getDefaultHandler()); // Start XSLT transformation and FOP processing transformer.transform(src, res); // Result processing FormattingResults foResults = fop.getResults(); java.util.List pageSequences = foResults.getPageSequences(); for (java.util.Iterator it = pageSequences.iterator(); it.hasNext();) { PageSequenceResults pageSequenceResults = (PageSequenceResults) it.next(); log.debug("PageSequence " + (String.valueOf(pageSequenceResults.getID()).length() > 0 ? pageSequenceResults.getID() : "<no id>") + " generated " + pageSequenceResults.getPageCount() + " pages."); } log.info("Generated " + foResults.getPageCount() + " PDF pages in total."); out.flush(); }
From source file:Main.java
/** * Formats a xml string// www .j av a 2 s . c o m * @param input * @param indent * @return */ public static String prettyFormatXml(String input, int indent) { try { Source xmlInput = new StreamSource(new StringReader(input)); StringWriter stringWriter = new StringWriter(); StreamResult xmlOutput = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", indent); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(xmlInput, xmlOutput); return xmlOutput.getWriter().toString(); } catch (Exception e) { e.printStackTrace(); } return input; }