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:elaborate.editor.export.tei.TeiMaker.java

public String toXML() {
    if (tei == null) {
        return null;
    }/*www  . j av  a2  s.co  m*/
    TransformerFactory transfac = TransformerFactory.newInstance();
    try {
        DOMSource source = new DOMSource(tei);
        Transformer trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        trans.setOutputProperty(OutputKeys.INDENT, "no");
        StringWriter sw = new StringWriter();
        StreamResult result = new StreamResult(sw);
        trans.transform(source, result);
        return sw.toString().replace("interpgrp>", "interpGrp>").replaceAll(" +<lb/>", "<lb/>");
    } catch (TransformerConfigurationException e) {
        e.printStackTrace();
    } catch (TransformerException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.github.caldav4j.methods.NewPropFindTest.java

private String ElementoString(Element node) throws TransformerException {
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    StreamResult result = new StreamResult(new StringWriter());
    DOMSource source = new DOMSource(node);
    transformer.transform(source, result);

    String xmlString = result.getWriter().toString();
    log.info(xmlString);/*  w  ww  .j a  v  a2  s  . c  om*/
    return xmlString;
}

From source file:com.bcmcgroup.flare.client.ClientUtil.java

/**
 * Convert a Document into a String/* w  w  w .  j av  a  2 s . com*/
 *
 * @param document           the Document to be converted to String
 * @param omitXmlDeclaration set to true if you'd like to omit the XML declaration, false otherwise
 * @return the String converted from a Document
 *
 */
public static String convertDocumentToString(Document document, boolean omitXmlDeclaration) {
    try {
        StringWriter stringWriter = new StringWriter();
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        Transformer transformer = transformerFactory.newTransformer();
        if (omitXmlDeclaration) {
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        } else {
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        }
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.INDENT, "no");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.transform(new DOMSource(document), new StreamResult(stringWriter));
        return stringWriter.toString();
    } catch (TransformerException e) {
        logger.error("Transformer Exception when attempting to convert a document to a string. ");
    }
    return null;
}

From source file:uk.ac.diamond.shibbolethecpauthclient.Utils.java

/**
 * Helper method that turns the message into a formatted XML string.
 * /*from  w w  w  . j  av  a2  s  .  c om*/
 * @param doc
 *The XML document to turn into a formatted XML string
 * 
 * @return The XML string
 */
static String xmlToString(Element doc) {

    StringWriter sw = new StringWriter();
    try {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

        transformer.transform(new DOMSource(doc), new StreamResult(sw));
        return sw.toString();
    } catch (TransformerException e) {
        LOG.error("Unable to print message contents: ", e);
        return "<ERROR: " + e.getMessage() + ">";
    }
}

From source file:org.n52.smartsensoreditor.controller.SaveLocalControllerSML.java

/**
 * Hanlde user request//from w  w w .j a v a2  s  . c  o m
 *
 * @param request
 * @param pResponse
 * @return
 * @throws Exception
 */
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse pResponse) throws Exception {
    // get document stored in backenservice
    Document lDoc = mBackendService.mergeBackend();
    XPathUtil lUtil = new XPathUtil();
    lUtil.setContext(editorContext);
    String lFileId = lUtil.evaluateAsString("//gmd:fileIdentifier/gco:CharacterString/text()", lDoc);
    if (lFileId.equals("")) {
        lFileId = lUtil.evaluateAsString("/*/gml:identifier/text()", lDoc);
    }
    lFileId = lFileId.trim();
    // set response attributes
    //pResponse.setContentType("application/x-download");
    pResponse.setContentType(getContentType() == null ? "application/x-download" : getContentType());
    // set header
    if (getSetHeader() != null) {
        for (Map.Entry<String, String> entry : getSetHeader().entrySet()) {
            pResponse.setHeader(entry.getKey(), entry.getValue());
        }
    }
    // add header
    if (getAddHeader() != null) {
        for (Map.Entry<String, String> entry : getAddHeader().entrySet()) {
            pResponse.addHeader(entry.getKey(), entry.getValue());
        }
    }
    pResponse.setHeader("Content-disposition", "attachment; filename=" + lFileId + ".xml");
    if (LOG.isDebugEnabled())
        LOG.debug("Preparing download for document with id: " + lFileId);
    ServletOutputStream lOutputStream = pResponse.getOutputStream();
    try {
        // write document to servlet response
        TransformerFactory tf = TransformerFactory.newInstance();
        // identity
        Transformer t = tf.newTransformer();
        t.setOutputProperty(OutputKeys.INDENT, "yes");
        t.transform(new DOMSource(lDoc), new StreamResult(lOutputStream));
    } catch (Exception e) {
        pResponse.setHeader("Content-disposition", "attachment; filename=ExportError.xml");
        lOutputStream.println("<?xml version='1.0' encoding=\"UTF-8\" standalone=\"no\" ?>");
        lOutputStream.println("<ExportExceptionReport version=\"1.1.0\">");
        lOutputStream.println("    Request rejected due to errors.");
        lOutputStream.println("      Reason: " + e.getMessage());
        lOutputStream.println("</ExportExceptionReport>");
        lOutputStream.println();
        LOG.error("Exception while copying from input to output stream: " + e.getMessage());
    } finally {
        lOutputStream.flush();
        lOutputStream.close();
    }
    // forward
    return null;
}

From source file:datascript.emit.xml.XmlExtension.java

public void generate(DataScriptEmitter emitter, TokenAST root) {
    if (parameters == null)
        throw new DataScriptException("No parameters set for XmlBackend!");

    if (!parameters.argumentExists("-xml")) {
        System.out.println("emitting XML file is disabled.");
        return;//www . j  a v  a  2  s.co  m
    }

    System.out.println("emitting xml");

    String fileName = parameters.getCommandLineArg("-xml");
    if (fileName == null) {
        fileName = "datascript.xml";
    }
    File outputFile = new File(parameters.getOutPathName(), fileName);
    this.rootNode = root;
    FileOutputStream os;
    try {
        os = new FileOutputStream(outputFile);
        TransformerFactory tf = TransformerFactory.newInstance();
        tf.setAttribute("indent-number", new Integer(2));
        Transformer t = tf.newTransformer();
        t.setOutputProperty(OutputKeys.INDENT, "yes");
        t.setOutputProperty(OutputKeys.METHOD, "xml");
        Source source = new SAXSource(this, new InputSource());
        Result result = new StreamResult(new OutputStreamWriter(os));
        t.transform(source, result);
    } catch (FileNotFoundException exc) {
        throw new DataScriptException(exc);
    } catch (TransformerConfigurationException exc) {
        throw new DataScriptException(exc);
    } catch (TransformerException exc) {
        throw new DataScriptException(exc);
    }
}

From source file:com.hangum.tadpole.engine.sql.util.export.XMLExporter.java

/**
 * make content file//from  ww  w.  j  a  v  a  2  s . c o m
 * 
 * @param tableName
 * @param rsDAO
 * @return
 * @throws Exception
 */
public static String makeContentFile(String tableName, QueryExecuteResultDTO rsDAO) throws Exception {
    String strTmpDir = PublicTadpoleDefine.TEMP_DIR + tableName + System.currentTimeMillis()
            + PublicTadpoleDefine.DIR_SEPARATOR;
    String strFile = tableName + ".xml";
    String strFullPath = strTmpDir + strFile;

    final StringWriter stWriter = new StringWriter();
    final List<Map<Integer, Object>> dataList = rsDAO.getDataList().getData();

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    final Document doc = builder.newDocument();
    final Element results = doc.createElement(tableName);
    doc.appendChild(results);

    Map<Integer, String> mapLabelName = rsDAO.getColumnLabelName();
    for (int i = 0; i < dataList.size(); i++) {
        Map<Integer, Object> mapColumns = dataList.get(i);
        Element row = doc.createElement("Row");
        results.appendChild(row);

        for (int j = 1; j < mapColumns.size(); j++) {
            String columnName = mapLabelName.get(j);
            String strValue = mapColumns.get(j) == null ? "" : "" + mapColumns.get(j);

            Element node = doc.createElement(columnName);
            node.appendChild(doc.createTextNode(strValue));
            row.appendChild(node);
        }
    }

    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);

    FileUtils.writeStringToFile(new File(strFullPath), stWriter.toString(), true);

    return strFullPath;
}

From source file:XMLUtils.java

public static void writeTo(Source src, OutputStream os, int indent, String charset, String omitXmlDecl) {
    Transformer it;//from  w  ww  .j  a v  a 2 s.co m
    try {

        //charset = "utf-8"; 

        it = newTransformer();
        it.setOutputProperty(OutputKeys.METHOD, "xml");
        if (indent > -1) {
            it.setOutputProperty(OutputKeys.INDENT, "yes");
            it.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", Integer.toString(indent));
        }
        it.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, omitXmlDecl);
        it.setOutputProperty(OutputKeys.ENCODING, charset);
        it.transform(src, new StreamResult(os));
    } catch (TransformerException e) {
        throw new RuntimeException("Failed to configure TRaX", e);
    }

}

From source file:net.sf.jabref.exporter.OpenDocumentSpreadsheetCreator.java

private static void exportOpenDocumentSpreadsheetXML(File tmpFile, BibDatabase database,
        List<BibEntry> entries) {
    OpenDocumentRepresentation od = new OpenDocumentRepresentation(database, entries);

    try (Writer ps = new OutputStreamWriter(new FileOutputStream(tmpFile), StandardCharsets.UTF_8)) {

        DOMSource source = new DOMSource(od.getDOMrepresentation());
        StreamResult result = new StreamResult(ps);
        Transformer trans = TransformerFactory.newInstance().newTransformer();
        trans.setOutputProperty(OutputKeys.INDENT, "yes");
        trans.transform(source, result);
    } catch (Exception e) {
        throw new Error(e);
    }/*from w  w w.j  av  a2s  .c  om*/
}

From source file:com.aurel.track.lucene.util.openOffice.OOIndexer.java

/**
 * Get the string content of an xml file
 *//*from w  w w .  j av a2  s.  c  o  m*/
public String parseXML(File file) {
    Document document = null;
    DocumentBuilderFactory documentBuilderfactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = null;
    try {
        builder = documentBuilderfactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        LOGGER.info("Building the document builder from factory failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
        return null;
    }
    try {
        document = builder.parse(file);
    } catch (SAXException e) {
        LOGGER.info("Parsing the XML document " + file.getPath() + " failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    } catch (IOException e) {
        LOGGER.info("Reading the XML document " + file.getPath() + " failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    if (document == null) {
        return null;
    }
    StringWriter result = new StringWriter();
    Transformer transformer = null;
    try {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformer = transformerFactory.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", "2");
    } catch (TransformerConfigurationException e) {
        LOGGER.warn(
                "Creating the transformer failed with TransformerConfigurationException: " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
        return null;
    }
    try {
        transformer.transform(new DOMSource(document), new StreamResult(result));
    } catch (TransformerException e) {
        LOGGER.warn("Transform failed with TransformerException: " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    return result.getBuffer().toString();
}