List of usage examples for javax.xml.transform OutputKeys ENCODING
String ENCODING
To view the source code for javax.xml.transform OutputKeys ENCODING.
Click Source Link
From source file:br.gov.lexml.parser.documentoarticulado.LexMLUtil.java
public static String formatLexML(String xml) { String retorno = null;//from w w w. j a va 2 s . com try { Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8")))); XPath xPath = XPathFactory.newInstance().newXPath(); NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']", document, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); ++i) { Node node = nodeList.item(i); node.getParentNode().removeChild(node); } Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); StringWriter stringWriter = new StringWriter(); StreamResult streamResult = new StreamResult(stringWriter); transformer.transform(new DOMSource(document), streamResult); retorno = stringWriter.toString(); } catch (Exception e) { e.printStackTrace(); } return retorno; }
From source file:it.polito.tellmefirst.web.rest.interfaces.AbsResponseInterface.java
public TransformerHandler initXMLDoc(ByteArrayOutputStream out) throws TMFOutputException { LOG.debug("[initXMLDoc] - BEGIN"); TransformerHandler hd;/*w w w .j av a 2 s . c o m*/ try { StreamResult streamResult = new StreamResult(out); SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); hd = tf.newTransformerHandler(); Transformer serializer = hd.getTransformer(); serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8"); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); hd.setResult(streamResult); hd.startDocument(); } catch (Exception e) { throw new TMFOutputException("Error initializing XML.", e); } LOG.debug("[initXMLDoc] - END"); return hd; }
From source file:com.aurel.track.exchange.docx.exporter.CustomXML.java
/** * @param items/*from w ww . java2s. c o m*/ * @return */ public static void convertToXml(OutputStream outputStream, Document dom) { Transformer transformer = null; try { TransformerFactory factory = TransformerFactory.newInstance(); transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); } catch (TransformerConfigurationException e) { LOGGER.error( "Creating the transformer failed with TransformerConfigurationException: " + e.getMessage()); return; } try { transformer.transform(new DOMSource(dom), new StreamResult(outputStream)); } catch (TransformerException e) { LOGGER.error("Transform failed with TransformerException: " + e.getMessage()); } }
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 {// w ww . java2 s . c o 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.mockey.storage.xml.MockeyXmlFactory.java
private String getDocumentAsString(Document document) throws IOException, TransformerException { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.ENCODING, HTTP.UTF_8); StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(document); transformer.transform(source, result); return result.getWriter().toString(); }
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 a2 s . 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:ch.entwine.weblounge.bridge.oaipmh.util.XmlGen.java
private void write(OutputStream out) { try {//from www . j a va2 s . c o m 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:com.sinet.gage.dlap.utils.XMLUtils.java
/** * @param String/*w w w . j av a 2 s .c o m*/ * @param String * @return String */ public static String parseXML(String xml, String rootElementName) { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); DocumentBuilder db; db = dbf.newDocumentBuilder(); Document newDoc = db.parse(new ByteArrayInputStream(xml.getBytes())); Element element = (Element) newDoc.getElementsByTagName(rootElementName).item(0); // Imports a node from another document to this document, // without altering Document newDoc2 = db.newDocument(); // or removing the source node from the original document Node copiedNode = newDoc2.importNode(element, true); // Adds the node to the end of the list of children of this node newDoc2.appendChild(copiedNode); Transformer tf = TransformerFactory.newInstance().newTransformer(); tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tf.setOutputProperty(OutputKeys.INDENT, "yes"); Writer out = new StringWriter(); tf.transform(new DOMSource(newDoc2), new StreamResult(out)); return out.toString(); } catch (TransformerException | ParserConfigurationException | SAXException | IOException e) { LOGGER.error("Exception in parsing xml from response: ", e); } return ""; }
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 w w .j a v a2s. co 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; } }
From source file:com.aurel.track.admin.customize.category.report.execute.ReportBeansToXML.java
/** * @param items/* w ww . j a va2 s . com*/ * @return */ public static void convertToXml(OutputStream outputStream, Document dom) { Transformer transformer = null; try { TransformerFactory factory = TransformerFactory.newInstance(); transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); } catch (TransformerConfigurationException e) { LOGGER.error( "Creating the transformer failed with TransformerConfigurationException: " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); return; } try { transformer.transform(new DOMSource(dom), new StreamResult(outputStream)); } catch (TransformerException e) { LOGGER.error("Transform failed with TransformerException: " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } }