Example usage for javax.xml.transform OutputKeys METHOD

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

Introduction

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

Prototype

String METHOD

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

Click Source Link

Document

method = "xml" | "html" | "text" | expanded name.

Usage

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

/**
 * Helper method that turns the message into a formatted XML string.
 * //from   w  ww.j  a  v  a  2  s  .  c o m
 * @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:XMLUtils.java

public static void writeTo(Source src, OutputStream os, int indent, String charset, String omitXmlDecl) {
    Transformer it;// w  ww  .  j a  va  2s .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: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;/*from   www  .  j  a  v a2s .  c om*/
    }

    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:net.sf.joost.trax.TransformerImpl.java

/**
 * Constructor//from ww w. j a  v a  2 s  .c om
 *
 * @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:com.alfaariss.oa.util.configuration.handler.text.PlainTextConfigurationHandler.java

/**
 * Writes the configuration to System.out.
 * @see IConfigurationHandler#saveConfiguration(org.w3c.dom.Document)
 *//* ww  w .jav  a2s.c  o m*/
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.hangum.tadpole.engine.sql.util.export.XMLExporter.java

/**
 * make content file/*from  www.  ja  v  a2s  . co  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:com.aurel.track.lucene.util.openOffice.OOIndexer.java

/**
 * Get the string content of an xml file
 *//*from  w  ww  .j a  v  a  2s.  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();
}

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

/**
 * Save the configuration to the file.//from w ww.  jav  a 2  s  .com
 * @see IConfigurationHandler#saveConfiguration(org.w3c.dom.Document)
 */
public void saveConfiguration(Document oConfigurationDocument) throws ConfigurationException {
    OutputStream os = null;
    try {
        os = new FileOutputStream(_fConfig);
        //create output format which uses new lines and tabs

        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(os));
    } catch (FileNotFoundException e) {
        _logger.error("Error writing configuration, file not found", e);
        throw new ConfigurationException(SystemErrors.ERROR_RESOURCE_CONNECT);
    } catch (TransformerException e) {
        _logger.error("Error while transforming document", e);
        throw new ConfigurationException(SystemErrors.ERROR_CONFIG_WRITE);
    } finally {

        try {
            if (os != null)
                os.close();
        } catch (IOException e) {
            _logger.debug("Error closing configuration outputstream", e);
        }
    }
}

From source file:XMLWriteTest.java

/**
 * Saves the drawing in SVG format, using DOM/XSLT
 *//* ww w  .  ja  va2 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

private static String nodeToString(final Node doc, final Properties outputProperties) {
    try {//from w ww  .  j a v a 2 s  .c  o  m
        final Transformer transformer = transformerFactory.newTransformer();
        outputProperties.put(OutputKeys.METHOD, "xml");
        outputProperties.put(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperties(outputProperties);
        final StringWriter writer = new StringWriter();
        transformer.transform(new DOMSource(doc), new StreamResult(writer));
        return writer.getBuffer().toString();
    } catch (final TransformerException e) {
        LOG.error(e.getMessage(), e);
    }
    return "";
}