List of usage examples for javax.xml.transform OutputKeys INDENT
String INDENT
To view the source code for javax.xml.transform OutputKeys INDENT.
Click Source Link
From source file:com.beligum.core.utils.Toolkit.java
public static String xmlToString(Document document, boolean indent) throws Exception { if (document == null) { return null; } else {//from w ww .ja v a 2 s. co m try { StringWriter sw = new StringWriter(); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.INDENT, indent ? "yes" : "no"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.transform(new DOMSource(document), new StreamResult(sw)); return sw.toString(); } catch (Exception e) { throw new Exception("Error converting XML to String", e); } } }
From source file:com.github.wesjd.overcastmappacker.xml.DocumentHandler.java
public DocumentHandler(File documentFile) { try {/*w w w . j a va 2 s . co m*/ Validate.isTrue(documentFile.exists(), "Document must exist for DocumentHandler to handle it."); Validate.isTrue(FilenameUtils.getExtension(documentFile.getPath()).equals("xml"), "Document supplied is not an XML file."); this.documentFile = documentFile; documentBuilder = XMLConstants.DOCUMENT_BUILDER_FACTORY.newDocumentBuilder(); document = documentBuilder.parse(new FileInputStream(documentFile)); transformer = XMLConstants.TRANSFORMER_FACTORY.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); } catch (ParserConfigurationException | IOException | SAXException | TransformerConfigurationException ex) { ex.printStackTrace(); } }
From source file:Main.java
/** * Serialise the supplied W3C DOM subtree. * * @param nodeList The DOM subtree as a NodeList. * @param format Format the output.//from ww w. j a v a 2 s.c o m * @param writer The target writer for serialization. * @throws DOMException Unable to serialise the DOM. */ public static void serialize(NodeList nodeList, boolean format, Writer writer) throws DOMException { if (nodeList == null) { throw new IllegalArgumentException("null 'subtree' NodeIterator arg in method call."); } try { TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer; if (format) { try { factory.setAttribute("indent-number", new Integer(4)); } catch (Exception e) { // Ignore... Xalan may throw on this!! // We handle Xalan indentation below (yeuckkk) ... } } transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); if (format) { transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", "4"); } int listLength = nodeList.getLength(); // Iterate through the Node List. for (int i = 0; i < listLength; i++) { Node node = nodeList.item(i); if (isTextNode(node)) { writer.write(node.getNodeValue()); } else if (node.getNodeType() == Node.ATTRIBUTE_NODE) { writer.write(((Attr) node).getValue()); } else if (node.getNodeType() == Node.ELEMENT_NODE) { transformer.transform(new DOMSource(node), new StreamResult(writer)); } } } catch (Exception e) { DOMException domExcep = new DOMException(DOMException.INVALID_ACCESS_ERR, "Unable to serailise DOM subtree."); domExcep.initCause(e); throw domExcep; } }
From source file:io.wcm.tooling.commons.contentpackagebuilder.ContentPackage.java
/** * @param os Output stream/*from ww w . j a v a 2 s.c o m*/ * @throws IOException */ ContentPackage(PackageMetadata metadata, OutputStream os) throws IOException { this.metadata = metadata; this.zip = new ZipOutputStream(os); this.transformerFactory = TransformerFactory.newInstance(); this.transformerFactory.setAttribute("indent-number", 2); try { this.transformer = transformerFactory.newTransformer(); this.transformer.setOutputProperty(OutputKeys.INDENT, "yes"); this.transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); } catch (TransformerException ex) { throw new RuntimeException("Failed to set up XML transformer: " + ex.getMessage(), ex); } this.xmlContentBuilder = new XmlContentBuilder(metadata.getXmlNamespaces()); buildPackageMetadata(); }
From source file:eionet.gdem.qa.engines.SaxonImpl.java
@Override protected void runQuery(XQScript script, OutputStream result) throws GDEMException { // Source sourceInput = null; // StringBuffer err_buf = new StringBuffer(); Configuration config = new Configuration(); // our own extension of Saxon's error listener to send feedback to the user SaxonListener listener = new SaxonListener(); config.setErrorListener(listener);/*from ww w.j av a 2s. c om*/ config.setURIResolver(new QAURIResolver()); config.setHostLanguage(Configuration.XQUERY); config.setLineNumbering(true); StaticQueryContext staticEnv = new StaticQueryContext(config); // staticEnv.setConfiguration(config); DynamicQueryContext dynamicEnv = new DynamicQueryContext(config); SaxonListener dynamicListener = new SaxonListener(); dynamicEnv.setErrorListener(dynamicListener); Properties outputProps = new Properties(); outputProps.setProperty(OutputKeys.INDENT, "no"); outputProps.setProperty(OutputKeys.ENCODING, DEFAULT_ENCODING); // if the output is html, then use method="xml" in output, otherwise, it's not valid xml if (getOutputType().equals(HTML_CONTENT_TYPE)) { outputProps.setProperty(OutputKeys.METHOD, XML_CONTENT_TYPE); } else { outputProps.setProperty(OutputKeys.METHOD, getOutputType()); } // add xml declaration only, if the output should be XML if (getOutputType().equals(XML_CONTENT_TYPE)) { outputProps.setProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); } else { outputProps.setProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); } String queriesPathURI = Utils.getURIfromPath(eionet.gdem.Properties.queriesFolder, true); if (queriesPathURI != null) { staticEnv.setBaseURI(queriesPathURI); } Reader queryReader = null; try { if (!Utils.isNullStr(script.getScriptSource())) { queryReader = new StringReader(script.getScriptSource()); } else if (!Utils.isNullStr(script.getScriptFileName())) { queryReader = new FileReader(script.getScriptFileName()); } else { throw new GDEMException("XQuery engine could not find script source or script file name!"); } // handle xq Parameters, extract from Saxon code if (script.getParams() != null) { for (int p = 0; p < script.getParams().length; p++) { String arg = script.getParams()[p]; int eq = arg.indexOf("="); if (eq < 1 || eq >= arg.length() - 1) { throw new GDEMException("Bad param=value pair"); // handleError("Bad param=value pair", true); } String argname = arg.substring(0, eq); if (argname.startsWith("!")) { // parameters starting with "!" are taken as output properties outputProps.setProperty(argname.substring(1), arg.substring(eq + 1)); } else if (argname.startsWith("+")) { // parameters starting with "+" are taken as inputdocuments // List sources = Transform.loadDocuments(arg.substring(eq+1), true, config); // dynamicEnv.setParameter(argname.substring(1), sources); } else { dynamicEnv.setParameter(argname, new StringValue(arg.substring(eq + 1))); } } } // compile XQuery XQueryExpression exp; try { exp = staticEnv.compileQuery(queryReader); staticEnv = exp.getStaticContext(); } catch (net.sf.saxon.trans.XPathException e) { throw e; } catch (java.io.IOException e) { throw e; } try { // evaluating XQuery exp.run(dynamicEnv, new StreamResult(result), outputProps); } catch (net.sf.saxon.trans.XPathException e) { listener.error(e); } } catch (Exception e) { String errMsg = (listener.hasErrors() ? listener.getErrors() : e.toString()); try { errMsg = parseErrors(errMsg, staticEnv); } catch (Exception ex) { LOGGER.error("Unable to parse exception string: " + ex.toString()); } LOGGER.error("==== CATCHED EXCEPTION " + errMsg, e); throw new GDEMException(errMsg, e); // listener.error(e); } finally { if (queryReader != null) { try { queryReader.close(); } catch (IOException e) { e.printStackTrace(); } } if (listener.hasErrors() || dynamicListener.hasErrors()) { String errMsg = listener.getErrors() + dynamicListener.getErrors(); try { errMsg = parseErrors(errMsg, staticEnv); } catch (Exception ex) { LOGGER.error("Unable to parse exception string: " + ex.toString()); } LOGGER.error(errMsg); throw new GDEMException(errMsg); } } }
From source file:Main.java
/** * DOCUMENT ME!//from ww w . j a va 2 s. c o m * * @return DOCUMENT ME! * * @throws TransformerConfigurationException DOCUMENT ME! * @throws TransformerException DOCUMENT ME! * @throws Exception DOCUMENT ME! */ public static byte[] writeToBytes(Document document) throws TransformerConfigurationException, TransformerException, Exception { byte[] ret = null; TransformerFactory tFactory = TransformerFactory.newInstance(); tFactory.setAttribute("indent-number", new Integer(4)); Transformer transformer = tFactory.newTransformer(); DOMSource source = new DOMSource(document); ByteArrayOutputStream bos = new ByteArrayOutputStream(); StreamResult result = new StreamResult(bos); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); // NOI18N transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // NOI18N transformer.setOutputProperty(OutputKeys.MEDIA_TYPE, "text/xml"); // NOI18N transformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); // NOI18N // indent the output to make it more legible... try { transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); // NOI18N transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // NOI18N } catch (IllegalArgumentException e) { // the JAXP implementation doesn't support indentation, no big deal //e.printStackTrace(); } try { transformer.transform(source, result); ret = bos.toByteArray(); } finally { if (bos != null) { bos.flush(); bos.close(); } } return ret; }
From source file:com.wavemaker.tools.pws.install.PwsInstall.java
public static void insertImport(File xmlFile, String resource) throws Exception { String content = getTrimmedXML(xmlFile); String fromStr1 = "<!DOCTYPE"; String toStr1 = "<!--!DOCTYPE"; content = content.replace(fromStr1, toStr1); String fromStr2 = "spring-beans-2.0.dtd\">"; String toStr2 = "spring-beans-2.0.dtd\"-->"; content = content.replace(fromStr2, toStr2); FileUtils.writeStringToFile(xmlFile, content, "UTF-8"); InputStream is = new FileInputStream(xmlFile); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true);// w ww. java 2s. com DocumentBuilder docBuilder = dbf.newDocumentBuilder(); Document doc = docBuilder.parse(is); doc = insertImport(doc, resource); Transformer t = TransformerFactory.newInstance().newTransformer(); t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); t.setOutputProperty(OutputKeys.INDENT, "yes"); t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); t.transform(new DOMSource(doc), new StreamResult(xmlFile)); content = FileUtils.readFileToString(xmlFile, "UTF-8"); content = content.replace(toStr1, fromStr1); content = content.replace(toStr2, fromStr2); FileUtils.writeStringToFile(xmlFile, content, "UTF-8"); }
From source file:ca.mcgill.music.ddmal.mei.MeiXmlWriter.java
/** * Construct and XML document and render it to the given stream. * @param os//from www.ja va 2s .c om * the output stream to render the XML document to. */ private void processDocument(OutputStream os) { try { Node rootNode = meiElementToNode(meiDocument.getRootElement()); document.appendChild(rootNode); TransformerFactory transformFact = TransformerFactory.newInstance(); Transformer transformer = transformFact.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(os); transformer.transform(source, result); } catch (TransformerException e) { } }
From source file:ch.entwine.weblounge.bridge.oaipmh.util.XmlGen.java
private void write(OutputStream out) { try {//ww w. ja va 2s . c om TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(out); transformer.transform(source, result); } catch (TransformerException e) { throw new RuntimeException(e); } }
From source file:net.mumie.coursecreator.xml.GraphXMLizer.java
/** * Describe <code>doTransform</code> method here. * * @param document a <code>Node</code> value * @return a <code>ByteArrayOutputStream</code> value * @exception TransformerException if an error occurs * @exception UnsupportedEncodingException if an error occurs *//*from w ww .j a va2 s . c o m*/ private static ByteArrayOutputStream doTransform(Node document) throws TransformerException, UnsupportedEncodingException { try { // Use a Transformer for output TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "US-ASCII"); DOMSource source = new DOMSource(document); ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStreamWriter out = new OutputStreamWriter(baos, "ASCII"); StreamResult result = new StreamResult(out); transformer.transform(source, result); return baos; } catch (TransformerException te) { // Error generated by the parser CCController.dialogErrorOccured("GraphXMLizer: TransformerException", "GraphXMLizer: TransformerException: " + te, JOptionPane.ERROR_MESSAGE); throw te; } }