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:Main.java
/** * Transforms a {@link Source} object into a {@link String} representation. * //w w w. j a v a2s. co m * @param xml the source input. * @param pretty if {@code true} then pretty print with white space. * @param writer write the string to this {@link Writer}. * @throws TransformerException */ public static void toString(Source xml, boolean pretty, Writer writer) throws TransformerException { final TransformerFactory factory = TransformerFactory.newInstance(); try { factory.setAttribute("{http://xml.apache.org/xalan}indent-amount", 2); } catch (IllegalArgumentException iae) { // try a different ident amount try { factory.setAttribute("indent-number", 2); } catch (IllegalArgumentException iae2) { // ignore } } final Transformer transformer = factory.newTransformer(); if (pretty) { transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8"); } transformer.transform(xml, new StreamResult(writer)); }
From source file:org.biopax.validator.api.ValidatorUtils.java
/** * Writes the multiple results report.//from w w w . ja va2 s .c o m * (as transformed XML). * * @param validatorResponse * @param writer */ public static void write(ValidatorResponse validatorResponse, Writer writer, Source xslt) { try { if (xslt != null) { Document doc = asDocument(validatorResponse); Source xmlSource = new DOMSource(doc); Result result = new StreamResult(writer); TransformerFactory transFact = TransformerFactory.newInstance(); Transformer trans = transFact.newTransformer(xslt); trans.setOutputProperty(OutputKeys.INDENT, "yes"); trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); trans.transform(xmlSource, result); } else { // write without any xslt getMarshaller().marshal(validatorResponse, writer); } } catch (Exception e) { throw new RuntimeException("Cannot transform/serialize/write: " + validatorResponse, e); } }
From source file:com.marklogic.client.functionaltest.TestBulkWriteWithTransformations.java
@Test public void testBulkLoadWithXSLTClientSideTransform() throws Exception { String docId[] = { "/transform/emp.xml", "/transform/food1.xml", "/transform/food2.xml" }; Source s[] = new Source[3]; s[0] = new StreamSource("src/test/java/com/marklogic/client/functionaltest/data/employee.xml"); s[1] = new StreamSource("src/test/java/com/marklogic/client/functionaltest/data/xml-original.xml"); s[2] = new StreamSource("src/test/java/com/marklogic/client/functionaltest/data/xml-original-test.xml"); // get the xslt Source xsl = new StreamSource( "src/test/java/com/marklogic/client/functionaltest/data/employee-stylesheet.xsl"); // create transformer TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(xsl); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); XMLDocumentManager docMgr = client.newXMLDocumentManager(); DocumentWriteSet writeset = docMgr.newWriteSet(); for (int i = 0; i < 3; i++) { SourceHandle handle = new SourceHandle(); handle.set(s[i]);// w w w. j a v a 2 s.co m // set the transformer handle.setTransformer(transformer); writeset.add(docId[i], handle); //Close handle. handle.close(); } docMgr.write(writeset); FileHandle dh = new FileHandle(); // DOMHandle dh = new DOMHandle(); docMgr.read(docId[0], dh); Scanner scanner = new Scanner(dh.get()).useDelimiter("\\Z"); String readContent = scanner.next(); assertTrue("xml document contains firstname", readContent.contains("firstname")); docMgr.read(docId[1], dh); Scanner sc1 = new Scanner(dh.get()).useDelimiter("\\Z"); readContent = sc1.next(); assertTrue("xml document contains firstname", readContent.contains("firstname")); docMgr.read(docId[2], dh); Scanner sc2 = new Scanner(dh.get()).useDelimiter("\\Z"); readContent = sc2.next(); assertTrue("xml document contains firstname", readContent.contains("firstname")); }
From source file:com.hydroLibCreator.action.Creator.java
private void buildDrumKitXML() { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try {/*w ww.j av a2 s . c o m*/ DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.newDocument(); } catch (ParserConfigurationException parserException) { parserException.printStackTrace(); } Element drumkit_info = document.createElement("drumkit_info"); document.appendChild(drumkit_info); Attr xmlns = document.createAttribute("xmlns"); xmlns.setValue("http://www.hydrogen-music.org/drumkit"); Attr xmlns_xsi = document.createAttribute("xmlns:xsi"); xmlns_xsi.setValue("http://www.w3.org/2001/XMLSchema-instance"); drumkit_info.setAttributeNode(xmlns); drumkit_info.setAttributeNode(xmlns_xsi); Node nameNode = createNameNode(document); drumkit_info.appendChild(nameNode); Node authorNode = createAuthorNode(document); drumkit_info.appendChild(authorNode); Node infoNode = createInfoNode(document); drumkit_info.appendChild(infoNode); Node licenseNode = createLicenseNode(document); drumkit_info.appendChild(licenseNode); Node instrumentListNode = createInstrumentListNode(document); drumkit_info.appendChild(instrumentListNode); // write the XML document to disk try { // create DOMSource for source XML document Source xmlSource = new DOMSource(document); // create StreamResult for transformation result Result result = new StreamResult(new FileOutputStream(destinationPath + "/drumkit.xml")); // create TransformerFactory TransformerFactory transformerFactory = TransformerFactory.newInstance(); // create Transformer for transformation Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); // transform and deliver content to client transformer.transform(xmlSource, result); } // handle exception creating TransformerFactory catch (TransformerFactoryConfigurationError factoryError) { System.err.println("Error creating " + "TransformerFactory"); factoryError.printStackTrace(); } catch (TransformerException transformerError) { System.err.println("Error transforming document"); transformerError.printStackTrace(); } catch (IOException ioException) { ioException.printStackTrace(); } }
From source file:com.c4om.utils.xmlutils.JavaXMLUtils.java
/** * Method that converts a W3C {@link Document} object to a String * @param document the document to convert * @param indent whether lines must be indented or not * @param omitDeclaration whether the XML declaration should be omitted or not. * @param encoding the encoding placed at the XML declaration. Be carefully: Specifying here an encoding only takes effect at the XML declaration. If you are going to write the string to an output stream (e.g. to a file), you must also take care of the encoding there, for example, by means of {@link org.apache.commons.io.output.XmlStreamWriter}. * @return the {@link String} representation of the document * @throws TransformerException if there are problems during the conversion *///from w w w . j ava 2 s .c o m public static String convertW3CDocumentToString(Document document, boolean indent, boolean omitDeclaration, String encoding) throws TransformerException { TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, omitDeclaration ? "yes" : "no"); transformer.setOutputProperty(OutputKeys.INDENT, indent ? "yes" : "no"); if (encoding != null) { transformer.setOutputProperty(OutputKeys.ENCODING, encoding); } StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(document), new StreamResult(writer)); String output = writer.getBuffer().toString(); return output; }
From source file:com.action.ExportAction.java
public String exportXMLAction() { try {/* w ww . j av a2s. c o m*/ //document DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.newDocument(); Element reportsElement = document.createElement("project");// reportsElement.setAttribute("date", (new Date()).toString()); document.appendChild(reportsElement); System.out.println("exportXMLAction:" + tableCode); String[] ids = tableCode.split(","); for (String id : ids) { System.out.println("id:" + id); List<JQ_zhibiao_entity> list = Export.getDuizhaoByJqTbCode(id); document = Export.exportXML(reportsElement, document, list, id); } TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); DOMSource source = new DOMSource(document); transformer.setOutputProperty(OutputKeys.ENCODING, "GB2312"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); PrintWriter pw = new PrintWriter(new FileOutputStream(realPath + "test.xml")); StreamResult result = new StreamResult(pw); transformer.transform(source, result); pw.close(); } catch (Exception e) { ActionContext.getContext().put("message", "??" + e); return ERROR; } return SUCCESS; }
From source file:Signing.java
private static void dumpDocument(Node root) throws TransformerException { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(new DOMSource(root), new StreamResult(System.out)); }//from ww w . j a v a2s . c o m
From source file:cz.cas.lib.proarc.common.export.archive.PackageBuilder.java
public PackageBuilder(File targetFolder) { this.parentFolder = targetFolder; this.pid2PhysicalDiv = new HashMap<String, DivType>(); try {/* w w w .java 2 s . c o m*/ this.xmlTypes = DatatypeFactory.newInstance(); this.domTransformer = TransformerFactory.newInstance().newTransformer(); this.domTransformer.setOutputProperty(OutputKeys.INDENT, "yes"); this.domTransformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); } catch (DatatypeConfigurationException ex) { throw new IllegalStateException(ex); } catch (TransformerConfigurationException ex) { throw new IllegalStateException(ex); } }
From source file:com.genericworkflownodes.knime.workflowexporter.export.impl.GuseKnimeWorkflowExporter.java
private String formatXml(final String unformattedXml) throws TransformerException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); // initialize StreamResult with File object to save to file final StreamResult result = new StreamResult(new StringWriter()); final StreamSource source = new StreamSource(new StringReader(unformattedXml)); transformer.transform(source, result); return result.getWriter().toString(); }
From source file:de.betterform.connector.xslt.XSLTSubmissionHandler.java
/** * Serializes and submits the specified instance data over the * <code>xslt</code> protocol. * * @param submission the submission issuing the request. * @param instance the instance data to be serialized and submitted. * @return xslt transformation result./* w w w . j av a2 s. c o m*/ * @throws XFormsException if any error occurred during submission. */ public Map submit(Submission submission, Node instance) throws XFormsException { try { if (LOGGER.isDebugEnabled()) { LOGGER.debug("uri: " + getURI()); } URI uri = ConnectorHelper.resolve(submission.getContainerObject().getProcessor().getBaseURI(), getURI()); Map parameters = ConnectorHelper.getURLParameters(uri); URI stylesheetURI = ConnectorHelper.removeURLParameters(uri); if (LOGGER.isDebugEnabled()) { LOGGER.debug("stylesheet uri: " + stylesheetURI); } // pass output properties from submission CachingTransformerService transformerService = (CachingTransformerService) getContext() .get(TransformerService.TRANSFORMER_SERVICE); if (transformerService == null) { if (uri.getScheme().equals("http")) { transformerService = new CachingTransformerService(new HttpResourceResolver()); } else if (uri.getScheme().equals("file")) { transformerService = new CachingTransformerService(new FileResourceResolver()); } else { throw new XFormsException( "Protocol " + stylesheetURI.getScheme() + " not supported for XSLT Submission Handler"); } } if (parameters != null && parameters.get("nocache") != null) { transformerService.setNoCache(true); } Transformer transformer = transformerService.getTransformer(stylesheetURI); if (submission.getVersion() != null) { transformer.setOutputProperty(OutputKeys.VERSION, submission.getVersion()); } if (submission.getIndent() != null) { transformer.setOutputProperty(OutputKeys.INDENT, Boolean.TRUE.equals(submission.getIndent()) ? "yes" : "no"); } if (submission.getMediatype() != null) { transformer.setOutputProperty(OutputKeys.MEDIA_TYPE, submission.getMediatype()); } if (submission.getEncoding() != null) { transformer.setOutputProperty(OutputKeys.ENCODING, submission.getEncoding()); } else { transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); } if (submission.getOmitXMLDeclaration() != null) { transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, Boolean.TRUE.equals(submission.getOmitXMLDeclaration()) ? "yes" : "no"); } if (submission.getStandalone() != null) { transformer.setOutputProperty(OutputKeys.STANDALONE, Boolean.TRUE.equals(submission.getStandalone()) ? "yes" : "no"); } if (submission.getCDATASectionElements() != null) { transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, submission.getCDATASectionElements()); } // pass parameters form uri if any if (parameters != null) { Iterator iterator = parameters.keySet().iterator(); String name; while (iterator.hasNext()) { name = (String) iterator.next(); transformer.setParameter(name, parameters.get(name)); } } // transform instance to byte array ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); long start = System.currentTimeMillis(); DOMSource domSource; //check for 'parse' param String parseParam = null; if (parameters.containsKey("parseString")) { parseParam = (String) parameters.get("parseString"); } if (parseParam != null && parseParam.equalsIgnoreCase("true")) { String xmlString = DOMUtil.getTextNodeAsString(instance); domSource = new DOMSource(DOMUtil.parseString(xmlString, true, false)); } else { domSource = new DOMSource(instance); } transformer.transform(domSource, new StreamResult(outputStream)); long end = System.currentTimeMillis(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("transformation time: " + (end - start) + " ms"); } // create input stream from result InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); Map response = new HashMap(); response.put(XFormsProcessor.SUBMISSION_RESPONSE_STREAM, inputStream); return response; } catch (Exception e) { throw new XFormsException(e); } }