Example usage for javax.xml.transform OutputKeys INDENT

List of usage examples for javax.xml.transform OutputKeys INDENT

Introduction

In this page you can find the example usage for javax.xml.transform OutputKeys INDENT.

Prototype

String INDENT

To view the source code for javax.xml.transform OutputKeys INDENT.

Click Source Link

Document

indent = "yes" | "no".

Usage

From source file:com.petercho.Encoder.java

public static String formatXml(String xml) throws TransformerException {
    Source xmlInput = new StreamSource(new StringReader(xml));
    StringWriter stringWriter = new StringWriter();
    StreamResult xmlOutput = new StreamResult(stringWriter);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    transformerFactory.setAttribute("indent-number", 4);
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.transform(xmlInput, xmlOutput);
    return xmlOutput.getWriter().toString();
}

From source file:com.alfaariss.oa.util.configuration.handler.text.PlainTextConfigurationHandler.java

/**
 * Writes the configuration to System.out.
 * @see IConfigurationHandler#saveConfiguration(org.w3c.dom.Document)
 *///from   w w  w.j  a v a 2 s  .  c  om
public void saveConfiguration(Document oConfigurationDocument) throws ConfigurationException {
    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.VERSION, "1.0");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(new DOMSource(oConfigurationDocument), new StreamResult(System.out));
    } catch (TransformerException e) {
        _logger.error("Error while transforming document", e);
        throw new ConfigurationException(SystemErrors.ERROR_CONFIG_WRITE);
    } catch (Exception e) {
        _logger.error("Internal error during write of configuration", e);
        throw new ConfigurationException(SystemErrors.ERROR_INTERNAL);
    }
}

From source file:com.qpark.eip.core.spring.PayloadLogger.java

/**
 * @return the//from   ww w . j a v a 2s .c o  m
 *         {@link org.springframework.integration.transformer.Transformer}
 * @throws TransformerConfigurationException
 */
private Transformer createNonIndentingTransformer() throws TransformerConfigurationException {
    final Transformer transformer = this.transformerHelper.createTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.INDENT, "no");
    return transformer;
}

From source file:de.pixida.logtest.reporting.XUnitReportGenerator.java

@Override
public void finish() {
    try {/* w ww .j  a  v a 2  s  .co m*/
        // Create document
        final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        docFactory.setNamespaceAware(true);
        final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // Create root element
        final Document doc = docBuilder.newDocument();
        final Element rootElement = doc.createElement("testsuite");
        rootElement.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        rootElement.setAttribute("xsi:schemaLocation",
                "https://maven.apache.org/surefire/maven-surefire-plugin/xsd/surefire-test-report.xsd");
        rootElement.setAttribute("name", "LogFileAnalysisTestsuite");
        final double msToSec = 1000.0;
        rootElement.setAttribute("time", String.valueOf(this.totalTimeMs / msToSec));
        final long numTests = this.results.size();
        final long numSuccesses = this.results.values().stream()
                .mapToLong(result -> result.stream().filter(r -> r.getMiddle().isSuccess()).count()).sum();
        final long numFailures = this.results.values().stream()
                .mapToLong(result -> result.stream().filter(r -> r.getMiddle().isFailure()).count()).sum();
        final long numSkipped = 0L;
        final long numErrors = numTests - numSuccesses - numFailures;
        rootElement.setAttribute("tests", String.valueOf(numTests));
        rootElement.setAttribute("errors", String.valueOf(numErrors));
        rootElement.setAttribute("skipped", String.valueOf(numSkipped));
        rootElement.setAttribute("failures", String.valueOf(numFailures));
        doc.appendChild(rootElement);

        // Create payload
        this.addProperties(doc, rootElement);
        this.addTestCases(doc, rootElement);

        // Dump results into file
        final TransformerFactory transformerFactory = TransformerFactory.newInstance();
        final Transformer transformer = transformerFactory.newTransformer();
        final DOMSource source = new DOMSource(doc);
        final File parentFile = this.destFile.getParentFile();
        if (parentFile != null) {
            parentFile.mkdirs(); // If fails, will be caught by the following operations
        }
        final StreamResult result = new StreamResult(this.destFile);
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.transform(source, result);
    } catch (final DOMException | TransformerException | ParserConfigurationException e) {
        LOG.error("Failed to write results", e);
    }
}

From source file:fr.arnaudguyon.xmltojsonlib.JsonToXml.java

/**
 *
 * @param indent size of the indent (number of spaces)
 * @return the formatted XML/*from  w ww.  jav a  2s.  c  o m*/
 */
public String toFormattedString(@IntRange(from = 0) int indent) {
    String input = toString();
    try {
        Source xmlInput = new StreamSource(new StringReader(input));
        StringWriter stringWriter = new StringWriter();
        StreamResult xmlOutput = new StreamResult(stringWriter);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "" + indent);
        transformer.transform(xmlInput, xmlOutput);
        return xmlOutput.getWriter().toString();
    } catch (Exception e) {
        throw new RuntimeException(e); // TODO: do my own
    }
}

From source file:com.krawler.formbuilder.servlet.workflowHandler.java

public String saveWorkFLow(HttpServletRequest request, HttpServletResponse response)
        throws ParserConfigurationException, TransformerConfigurationException, TransformerException {
    try {//  w  ww  .  java 2 s  . c om

        String workflow = request.getParameter("jsonnodeobj");
        String linejson = request.getParameter("linejson");
        String processId = request.getParameter("flowid");
        String containerId = request.getParameter("containerId");
        this.parentSplit = request.getParameter("parentSplit");

        String path = ConfigReader.getinstance().get("workflowpath") + processId;

        File fdir = new File(path);
        if (!fdir.exists()) {
            fdir.mkdirs();
        }
        File file = new File(fdir + System.getProperty("file.separator") + "bpmn.xml");
        if (file.exists()) {
            file.delete();
        }

        Writer output = new BufferedWriter(new FileWriter(file));

        JSONObject jsonobj = new JSONObject(workflow);
        JSONObject json_line = new JSONObject(linejson);
        createDocument();
        writeXml(jsonobj, containerId, processId, json_line);

        TransformerFactory transfac = TransformerFactory.newInstance();
        Transformer trans1 = transfac.newTransformer();
        trans1.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        trans1.setOutputProperty(OutputKeys.INDENT, "yes");

        StringWriter sw = new StringWriter();
        StreamResult kwcresult = new StreamResult(sw);
        DOMSource kwcsource = new DOMSource(dom);
        trans1.transform(kwcsource, kwcresult);

        output.write(sw.toString());

        output.close();
        return "{success:true}";
    } catch (JSONException ex) {
        logger.warn(ex.getMessage(), ex);
        return "{success:true}";
    } catch (IOException ex) {
        logger.warn(ex.getMessage(), ex);
        return "{success:false}";
    }
}

From source file:fr.aliasource.webmail.server.proxy.client.http.DOMUtils.java

public static void serialise(Document doc, OutputStream out) throws TransformerException {
    TransformerFactory fac = TransformerFactory.newInstance();
    Transformer tf = fac.newTransformer();
    tf.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
    Source input = new DOMSource(doc.getDocumentElement());
    Result output = new StreamResult(out);
    tf.transform(input, output);/*from   ww w  .j  ava2s.c  om*/
}

From source file:net.sf.joost.trax.TransformerImpl.java

/**
 * Constructor//w w  w . ja  v  a2s.c  o  m
 *
 * @param processor A <code>Processor</code> object.
 */
protected TransformerImpl(Processor processor) {
    this.processor = processor;

    // set tracing manager on processor object
    if (processor instanceof DebugProcessor) {
        DebugProcessor dbp = (DebugProcessor) processor;
        dbp.setTraceManager(traceManager);
        dbp.setTransformer(this);

        Emitter emitter = processor.getEmitter();
        if (emitter instanceof DebugEmitter) {
            ((DebugEmitter) emitter).setTraceManager(traceManager);
        }
    }
    supportedProperties.add(OutputKeys.ENCODING);
    supportedProperties.add(OutputKeys.MEDIA_TYPE);
    supportedProperties.add(OutputKeys.METHOD);
    supportedProperties.add(OutputKeys.OMIT_XML_DECLARATION);
    supportedProperties.add(OutputKeys.STANDALONE);
    supportedProperties.add(OutputKeys.VERSION);
    supportedProperties.add(TrAXConstants.OUTPUT_KEY_SUPPORT_DISABLE_OUTPUT_ESCAPING);

    ignoredProperties.add(OutputKeys.CDATA_SECTION_ELEMENTS);
    ignoredProperties.add(OutputKeys.DOCTYPE_PUBLIC);
    ignoredProperties.add(OutputKeys.DOCTYPE_SYSTEM);
    ignoredProperties.add(OutputKeys.INDENT);
}

From source file:XMLWriteTest.java

/**
 * Saves the drawing in SVG format, using DOM/XSLT
 *///from w ww. ja v  a  2 s .  c  o  m
public void saveDocument() throws TransformerException, IOException {
    if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION)
        return;
    File f = chooser.getSelectedFile();
    Document doc = comp.buildDocument();
    Transformer t = TransformerFactory.newInstance().newTransformer();
    t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,
            "http://www.w3.org/TR/2000/CR-SVG-20000802/DTD/svg-20000802.dtd");
    t.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//W3C//DTD SVG 20000802//EN");
    t.setOutputProperty(OutputKeys.INDENT, "yes");
    t.setOutputProperty(OutputKeys.METHOD, "xml");
    t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    t.transform(new DOMSource(doc), new StreamResult(new FileOutputStream(f)));
}

From source file:eu.scidipes.toolkits.palibrary.utils.XMLUtils.java

/**
 * Converts a {@Node} instance into a readable <code>String</code> with optional formatting and XML
 * declaration/*from ww  w .  j  a v  a  2  s  . c o m*/
 * 
 * @param doc
 * @param indentAndFormat
 * @param omitXmlDeclaration
 * @return the node contents as a String
 */
public static String nodeToString(final Node doc, final boolean indentAndFormat,
        final boolean omitXmlDeclaration) {
    final Properties outputProperties = new Properties();
    outputProperties.put(OutputKeys.INDENT, indentAndFormat ? "yes" : "no");
    outputProperties.put(OutputKeys.OMIT_XML_DECLARATION, omitXmlDeclaration ? "yes" : "no");
    outputProperties.put("{http://xml.apache.org/xslt}indent-amount", indentAndFormat ? "2" : "0");
    return nodeToString(doc, outputProperties);
}