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:org.dataone.proto.trove.mn.http.client.HttpExceptionHandler.java
private static String domToString(Document document) throws ParserConfigurationException, TransformerConfigurationException, TransformerException { DocumentBuilder documentBuilder = null; Transformer transformer = null; StringWriter strWtr = new StringWriter(); documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //xml, html, text transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); String result = null;/*from ww w . j a v a 2s.c o m*/ if (document != null) { StreamResult strResult = new StreamResult(strWtr); transformer.transform(new DOMSource(document.getDocumentElement()), strResult); result = strResult.getWriter().toString(); } return result; }
From source file:be.fedict.eid.applet.service.signer.ooxml.RelationshipTransformService.java
private OctetStreamData toOctetStreamData(Node node) throws TransformerException { Source source = new DOMSource(node); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Result result = new StreamResult(outputStream); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.transform(source, result); LOG.debug("result: " + new String(outputStream.toByteArray())); return new OctetStreamData(new ByteArrayInputStream(outputStream.toByteArray())); }
From source file:com.google.enterprise.connector.salesforce.BaseTraversalManager.java
/** * Converts the <document></document> xml into a BaseSimpleDocument object * that we can send into a documentList object that ultimately gets returned * to the connector-manager// ww w .ja v a2 s.co m * * @param inxml * the xml form of and individual <document></document> object */ private BaseSimpleDocument convertXMLtoBaseDocument(Document doc) { try { HashMap hm_spi = new HashMap(); HashMap hm_meta_tags = new HashMap(); Map props = new HashMap(); String content_value = ""; TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // TODO: figure out why the initial doc passed in to the method // doesn't have the stylesheet 'fully' applied // this is why we do the conversion back and forth below // because for some reason the doc->string->doc has the stylesheet // applied. String sdoc = Util.XMLDoctoString(doc); logger.log(Level.FINEST, "About to convert STORE XML to BaseDocument " + sdoc); doc = Util.XMLStringtoDoc(sdoc); NodeList nl_document = doc.getElementsByTagName("document"); Node ndoc = nl_document.item(0); NodeList nl_doc_child = ndoc.getChildNodes(); for (int j = 0; j < nl_doc_child.getLength(); j++) { Node cnode = nl_doc_child.item(j); String doc_child_node_name = cnode.getNodeName(); if (doc_child_node_name.equalsIgnoreCase("spiheaders")) { NodeList nl_spi = cnode.getChildNodes(); for (int k = 0; k < nl_spi.getLength(); k++) { Node n_spi = nl_spi.item(k); if (n_spi.getNodeType() == Node.ELEMENT_NODE) { String spi_name = n_spi.getAttributes().getNamedItem("name").getNodeValue(); String spi_value = ""; if (n_spi.getFirstChild() != null) { spi_value = n_spi.getFirstChild().getNodeValue(); logger.log(Level.FINEST, "Adding SPI " + spi_name + " " + spi_value); } hm_spi.put(spi_name, spi_value); } } } if (doc_child_node_name.equalsIgnoreCase("metadata")) { NodeList nl_meta = cnode.getChildNodes(); for (int k = 0; k < nl_meta.getLength(); k++) { Node n_meta = nl_meta.item(k); if (n_meta.getNodeType() == Node.ELEMENT_NODE) { String meta_name = n_meta.getAttributes().getNamedItem("name").getNodeValue(); String meta_value = ""; if (n_meta.getFirstChild() != null) { meta_value = n_meta.getFirstChild().getNodeValue(); logger.log(Level.FINEST, "Adding METATAG " + meta_name + " " + meta_value); } hm_meta_tags.put(meta_name, meta_value); } } } if (doc_child_node_name.equalsIgnoreCase("content")) { content_value = cnode.getChildNodes().item(0).getNodeValue(); String encoding_type = ""; NamedNodeMap attribs = cnode.getAttributes(); if (attribs.getLength() > 0) { Node attrib = attribs.getNamedItem("encoding"); if (attrib != null) encoding_type = attrib.getNodeValue(); if (encoding_type.equalsIgnoreCase("base64") || encoding_type.equalsIgnoreCase("base64binary")) { byte[] b = org.apache.commons.codec.binary.Base64 .decodeBase64(content_value.getBytes()); ByteArrayInputStream input1 = new ByteArrayInputStream(b); logger.log(Level.FINEST, "Adding base64 encoded CONTENT " + content_value); props.put(SpiConstants.PROPNAME_CONTENT, input1); } else { logger.log(Level.FINEST, "Adding Text/HTML CONTENT " + content_value); props.put(SpiConstants.PROPNAME_CONTENT, content_value); } } else { logger.log(Level.FINEST, "Adding default Text/HTML CONTENT " + content_value); props.put(SpiConstants.PROPNAME_CONTENT, content_value); } } } // the hashmap holding the spi headers Iterator itr_spi = hm_spi.keySet().iterator(); while (itr_spi.hasNext()) { String key = (String) itr_spi.next(); String value = (String) hm_spi.get(key); if (key.equals("DEFAULT_MIMETYPE")) props.put(SpiConstants.DEFAULT_MIMETYPE, value); if (key.equals("PROPNAME_ACTION")) props.put(SpiConstants.PROPNAME_ACTION, value); if (key.equals("PROPNAME_CONTENTURL")) props.put(SpiConstants.PROPNAME_CONTENTURL, value); if (key.equals("PROPNAME_DISPLAYURL")) props.put(SpiConstants.PROPNAME_DISPLAYURL, value); if (key.equals("PROPNAME_DOCID")) props.put(SpiConstants.PROPNAME_DOCID, value); if (key.equals("PROPNAME_ISPUBLIC")) props.put(SpiConstants.PROPNAME_ISPUBLIC, value); if (key.equals("PROPNAME_LASTMODIFIED")) props.put(SpiConstants.PROPNAME_LASTMODIFIED, value); if (key.equals("PROPNAME_MIMETYPE")) props.put(SpiConstants.PROPNAME_MIMETYPE, value); // if (key.equals("PROPNAME_SEARCHURL")) // props.put(SpiConstants.PROPNAME_SEARCHURL, value); // if (key.equals("PROPNAME_SECURITYTOKEN")) // props.put(SpiConstants.PROPNAME_SECURITYTOKEN, value); } // hashmap holding the custom metatags Iterator itr_meta = hm_meta_tags.keySet().iterator(); while (itr_meta.hasNext()) { String key = (String) itr_meta.next(); String value = (String) hm_meta_tags.get(key); props.put(key, value); } BaseSimpleDocument bsd = createSimpleDocument(new Date(), props); return bsd; } catch (Exception ex) { logger.log(Level.SEVERE, "Error " + ex); } return null; }
From source file:org.openmrs.module.atomfeed.AtomFeedUtil.java
/** * Converts the given object to an xml entry * /* ww w. ja v a 2s . c o m*/ * @param action what is happenening * @param object the object being changed * @return atom feed xml entry string * @should return valid entry xml data */ protected static String getEntry(String action, OpenmrsObject object) { try { // We need a Document DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); Document doc = docBuilder.newDocument(); // ////////////////////// // Creating the XML tree // create the root element and add it to the document Element root = doc.createElement("entry"); doc.appendChild(root); // the title element is REQUIRED // create title element, add object class, and add to root Element title = doc.createElement("title"); Text titleText = doc.createTextNode(action + ":" + object.getClass().getName()); title.appendChild(titleText); root.appendChild(title); // create link to view object details Element link = doc.createElement("link"); link.setAttribute("href", AtomFeedUtil.getViewUrl(object)); root.appendChild(link); // the id element is REQUIRED // create id element Element id = doc.createElement("id"); Text idText = doc.createTextNode("urn:uuid:" + object.getUuid()); id.appendChild(idText); root.appendChild(id); // the updated element is REQUIRED // create updated element, set current date Element updated = doc.createElement("updated"); // TODO: try to discover dateChanged/dateCreated from object -- ATOM-2 // instead? Text updatedText = doc.createTextNode(dateToRFC3339(getUpdatedValue(object))); updated.appendChild(updatedText); root.appendChild(updated); // the author element is REQUIRED // add author element, find creator Element author = doc.createElement("author"); Element name = doc.createElement("name"); Text nameText = doc.createTextNode(getAuthor(object)); name.appendChild(nameText); author.appendChild(name); root.appendChild(author); // the summary element is REQUIRED // add a summary Element summary = doc.createElement("summary"); Text summaryText = doc.createTextNode(object.getClass().getSimpleName() + " -- " + action); summary.appendChild(summaryText); root.appendChild(summary); Element classname = doc.createElement("classname"); Text classnameText = doc.createTextNode(object.getClass().getName()); classname.appendChild(classnameText); root.appendChild(classname); Element actionElement = doc.createElement("action"); Text actionText = doc.createTextNode(action); actionElement.appendChild(actionText); root.appendChild(actionElement); /* * Print the xml to the string */ // set up a transformer TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); trans.setOutputProperty(OutputKeys.INDENT, "no"); StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); DOMSource source = new DOMSource(doc); trans.transform(source, result); return sw.toString(); } catch (Exception e) { log.error("unable to create entry string for: " + object); return ""; } }
From source file:com.krawler.portal.tools.ServiceBuilder.java
public void createModuleDef(ArrayList list, String classname) { String result = ""; try {//from w ww .ja v a2s. c o m DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); Document doc = docBuilder.parse((new ClassPathResource("logic/moduleEx.xml").getFile())); //Document doc = docBuilder.newDocument(); NodeList modules = doc.getElementsByTagName("modules"); Node modulesNode = modules.item(0); Element module_ex = doc.getElementById(classname); if (module_ex != null) { modulesNode.removeChild(module_ex); } Element module = doc.createElement("module"); Element property_list = doc.createElement("property-list"); module.setAttribute("class", "com.krawler.esp.hibernate.impl." + classname); module.setAttribute("type", "pojo"); module.setAttribute("id", classname); for (int cnt = 0; cnt < list.size(); cnt++) { Element propertyNode = doc.createElement("property"); Hashtable mapObj = (Hashtable) list.get(cnt); propertyNode.setAttribute("name", mapObj.get("name").toString()); propertyNode.setAttribute("type", mapObj.get("type").toString().toLowerCase()); property_list.appendChild(propertyNode); } module.appendChild(property_list); modulesNode.appendChild(module); TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); trans.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//KRAWLER//DTD BUSINESSRULES//EN"); trans.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "http://192.168.0.4/dtds/module.dtd"); trans.setOutputProperty(OutputKeys.VERSION, "1.0"); trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // create string from xml tree File outputFile = (new ClassPathResource("logic/moduleEx.xml").getFile()); outputFile.setWritable(true); // StringWriter sw = new StringWriter(); StreamResult sresult = new StreamResult(outputFile); DOMSource source = new DOMSource(doc); trans.transform(source, sresult); // result = sw.toString(); } catch (SAXException ex) { logger.warn(ex.getMessage(), ex); } catch (IOException ex) { logger.warn(ex.getMessage(), ex); } catch (TransformerException ex) { logger.warn(ex.getMessage(), ex); } catch (ParserConfigurationException ex) { logger.warn(ex.getMessage(), ex); } finally { // System.out.println(result); // return result; } }
From source file:org.opengeoportal.proxy.controllers.OldDynamicOgcController.java
private String xmlToString(Node node) throws TransformerException { StringWriter stw = new StringWriter(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.transform(new DOMSource(node), new StreamResult(stw)); return stw.toString(); }
From source file:com.legstar.cob2xsd.Cob2Xsd.java
/** * Serialize the XML Schema to a string. * <p/>/* ww w .j a v a 2s. com*/ * If we are provided with an XSLT customization file then we transform the * XMLSchema. * * @param xsd the XML Schema before customization * @return a string serialization of the customized XML Schema * @throws XsdGenerationException if customization fails */ public String xsdToString(final XmlSchema xsd) throws XsdGenerationException { if (_log.isDebugEnabled()) { StringWriter writer = new StringWriter(); xsd.write(writer); debug("6. Writing XML Schema: ", writer.toString()); } String errorMessage = "Customizing XML Schema failed."; try { TransformerFactory tFactory = TransformerFactory.newInstance(); try { tFactory.setAttribute("indent-number", "4"); } catch (IllegalArgumentException e) { _log.debug("Unable to set indent-number on transfomer factory", e); } StringWriter writer = new StringWriter(); Source source = new DOMSource(xsd.getAllSchemas()[0]); Result result = new StreamResult(writer); Transformer transformer; String xsltFileName = getModel().getCustomXsltFileName(); if (xsltFileName == null || xsltFileName.trim().length() == 0) { transformer = tFactory.newTransformer(); } else { Source xsltSource = new StreamSource(new File(xsltFileName)); transformer = tFactory.newTransformer(xsltSource); } transformer.setOutputProperty(OutputKeys.ENCODING, getModel().getXsdEncoding()); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.STANDALONE, "no"); transformer.transform(source, result); writer.flush(); return writer.toString(); } catch (TransformerConfigurationException e) { _log.error(errorMessage, e); throw new XsdGenerationException(e); } catch (TransformerFactoryConfigurationError e) { _log.error(errorMessage, e); throw new XsdGenerationException(e); } catch (TransformerException e) { _log.error(errorMessage, e); throw new XsdGenerationException(e); } }
From source file:com.hangum.tadpole.engine.sql.util.QueryUtils.java
/** * query to xml/* w w w .ja va2s. c o m*/ * * @param userDB * @param strQuery * @param listParam */ @SuppressWarnings("deprecation") public static String selectToXML(final UserDBDAO userDB, final String strQuery, final List<Object> listParam) throws Exception { final StringWriter stWriter = new StringWriter(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); final Document doc = builder.newDocument(); final Element results = doc.createElement("Results"); doc.appendChild(results); SqlMapClient client = TadpoleSQLManager.getInstance(userDB); QueryRunner qr = new QueryRunner(client.getDataSource()); qr.query(strQuery, listParam.toArray(), new ResultSetHandler<Object>() { @Override public Object handle(ResultSet rs) throws SQLException { ResultSetMetaData metaData = rs.getMetaData(); while (rs.next()) { Element row = doc.createElement("Row"); results.appendChild(row); for (int i = 1; i <= metaData.getColumnCount(); i++) { String columnName = metaData.getColumnName(i); Object value = rs.getObject(i) == null ? "" : rs.getObject(i); Element node = doc.createElement(columnName); node.appendChild(doc.createTextNode(value.toString())); row.appendChild(node); } } return stWriter.toString(); } }); DOMSource domSource = new DOMSource(doc); TransformerFactory tf = TransformerFactory.newInstance(); tf.setAttribute("indent-number", 4); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");//"ISO-8859-1"); StreamResult sr = new StreamResult(stWriter); transformer.transform(domSource, sr); return stWriter.toString(); }
From source file:com.messagehub.samples.servlet.KafkaServlet.java
public String toPrettyString(String xml, int indent) { try {// ww w. ja v a2 s.c o m // Turn xml string into a document Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8")))); // Remove whitespaces outside tags 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); } // Setup pretty print options TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", indent); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // Return pretty print xml string StringWriter stringWriter = new StringWriter(); transformer.transform(new DOMSource(document), new StreamResult(stringWriter)); return stringWriter.toString(); } catch (Exception e) { throw new RuntimeException(e); } }