List of usage examples for javax.xml.transform OutputKeys OMIT_XML_DECLARATION
String OMIT_XML_DECLARATION
To view the source code for javax.xml.transform OutputKeys OMIT_XML_DECLARATION.
Click Source Link
From source file:com.adobe.acs.commons.components.longformtext.impl.LongFormTextComponentImpl.java
@Override public final String[] getTextParagraphs(final String text) { List<String> paragraphs = new ArrayList<String>(); try {//w w w . j a v a 2s . c o m final Document doc = htmlParser.parse(null, IOUtils.toInputStream(text), "UTF-8"); doc.getDocumentElement().normalize(); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); final NodeList bodies = doc.getElementsByTagName("body"); if (bodies != null && bodies.getLength() == 1) { final org.w3c.dom.Node body = bodies.item(0); final NodeList children = body.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); final org.w3c.dom.Node child = children.item(i); if (child == null) { log.warn("Found a null dom node."); continue; } else if (child.getNodeType() != org.w3c.dom.Node.ELEMENT_NODE) { log.warn("Found a dom node is not an element; skipping"); continue; } stripNamespaces(child); transformer.transform(new DOMSource(child), result); writer.flush(); final String outerHTML = writer.toString(); if (StringUtils.isNotBlank(outerHTML)) { paragraphs.add(outerHTML); } } } else { log.debug("HTML does not have a single body tag. Cannot parse as expected."); } } catch (Exception e) { log.warn("Long Form Text encountered a parser error: {}", e); } return paragraphs.toArray(new String[paragraphs.size()]); }
From source file:no.digipost.api.interceptors.SoapLog.java
private Transformer createNonIndentingTransformer() throws TransformerConfigurationException { Transformer transformer = createTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "no"); return transformer; }
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 w w w . j a va2s . co 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:eu.domibus.common.util.xmladapter.ToStringAdapter.java
private String nodeToString(Node node) { StringWriter sw = new StringWriter(); try {//from w w w .j a v a 2 s . c o m Transformer t = this.transformerFactory.newTransformer(); t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); t.transform(new DOMSource(node), new StreamResult(sw)); } catch (TransformerException e) { throw new ConfigurationException(e); } return sw.toString(); }
From source file:net.sf.joost.emitter.XmlEmitter.java
/** Constructor */ public XmlEmitter(Writer writer, String encoding, Properties outputProperties) { super(writer, encoding); if (outputProperties != null) { String val; val = outputProperties.getProperty(OutputKeys.OMIT_XML_DECLARATION); if (val != null) propOmitXmlDeclaration = val.equals("yes"); if (!encoding.equals("UTF-8") && !encoding.equals("UTF-16")) propOmitXmlDeclaration = false; val = outputProperties.getProperty(OutputKeys.STANDALONE); if (val != null) propStandalone = val.equals("yes"); val = outputProperties.getProperty(OutputKeys.VERSION); if (val != null) propVersion = val; }// w ww . jav a 2 s . co m }
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);/*from ww w .jav a2 s . c om*/ 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:ApplyXPath.java
/** Process input args and execute the XPath. */ public void doMain(String[] args) throws Exception { filename = args[0];// w ww . j av a 2 s . c o m xpath = args[1]; if ((filename != null) && (filename.length() > 0) && (xpath != null) && (xpath.length() > 0)) { // Tell that we're loading classes and parsing, so the time it // takes to do this doesn't get confused with the time to do // the actual query and serialization. System.out.println("Loading classes, parsing " + filename + ", and setting up serializer"); // Set up a DOM tree to query. InputSource in = new InputSource(new FileInputStream(filename)); DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); dfactory.setNamespaceAware(true); Document doc = dfactory.newDocumentBuilder().parse(in); // Set up an identity transformer to use as serializer. Transformer serializer = TransformerFactory.newInstance().newTransformer(); serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); // Use the simple XPath API to select a nodeIterator. System.out.println("Querying DOM using " + xpath); NodeIterator nl = XPathAPI.selectNodeIterator(doc, xpath); // Serialize the found nodes to System.out. System.out.println("<output>"); Node n; while ((n = nl.nextNode()) != null) { if (isTextNode(n)) { // DOM may have more than one node corresponding to a // single XPath text node. Coalesce all contiguous text nodes // at this level StringBuffer sb = new StringBuffer(n.getNodeValue()); for (Node nn = n.getNextSibling(); isTextNode(nn); nn = nn.getNextSibling()) { sb.append(nn.getNodeValue()); } System.out.print(sb); } else { serializer.transform(new DOMSource(n), new StreamResult(new OutputStreamWriter(System.out))); } System.out.println(); } System.out.println("</output>"); } else { System.out.println("Bad input args: " + filename + ", " + xpath); } }
From source file:ApplyXPathDOM.java
/** Process input args and execute the XPath. */ public void doMain(String[] args) throws Exception { filename = args[0];//from w ww . ja v a 2 s . c o m xpath = args[1]; if ((filename != null) && (filename.length() > 0) && (xpath != null) && (xpath.length() > 0)) { // Tell that we're loading classes and parsing, so the time it // takes to do this doesn't get confused with the time to do // the actual query and serialization. System.out.println("Loading classes, parsing " + filename + ", and setting up serializer"); // Set up a DOM tree to query. InputSource in = new InputSource(new FileInputStream(filename)); DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); dfactory.setNamespaceAware(true); Document doc = dfactory.newDocumentBuilder().parse(in); // Set up an identity transformer to use as serializer. Transformer serializer = TransformerFactory.newInstance().newTransformer(); serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); // Use the DOM L3 XPath API to apply the xpath expression to the doc. System.out.println("Querying DOM using " + xpath); // Create an XPath evaluator and pass in the document. XPathEvaluator evaluator = new XPathEvaluatorImpl(doc); XPathNSResolver resolver = evaluator.createNSResolver(doc); // Evaluate the xpath expression XPathResult result = (XPathResult) evaluator.evaluate(xpath, doc, resolver, XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null); // Serialize the found nodes to System.out. System.out.println("<output>"); Node n; while ((n = result.iterateNext()) != null) { if (isTextNode(n)) { // DOM may have more than one node corresponding to a // single XPath text node. Coalesce all contiguous text nodes // at this level StringBuffer sb = new StringBuffer(n.getNodeValue()); for (Node nn = n.getNextSibling(); isTextNode(nn); nn = nn.getNextSibling()) { sb.append(nn.getNodeValue()); } System.out.print(sb); } else { serializer.transform(new DOMSource(n), new StreamResult(new OutputStreamWriter(System.out))); } System.out.println(); } System.out.println("</output>"); } else { System.out.println("Bad input args: " + filename + ", " + xpath); } }
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 w w w.j av a2s . c o m*/ 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:com.casewaresa.framework.util.LegacyJasperInputStream.java
public static String addDocTypeAndConvertDOMToString(final Document document) { TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = null;//from w w w. jav a 2 s . com try { trans = transfac.newTransformer(); } catch (TransformerConfigurationException ex) { log.error(ex.getMessage(), ex); } trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); trans.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "//JasperReports//DTD Report Design//EN"); trans.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd"); StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); DOMSource source = new DOMSource(document); try { trans.transform(source, result); } catch (TransformerException ex) { log.error(ex.getMessage(), ex); } return sw.toString(); }