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:cz.cas.lib.proarc.common.export.mets.MetsUtils.java

/**
 *
 * Transforms the xml document to a string
 *
 * @param doc//from ww w . j a  v  a2  s .c om
 * @return
 */
public static String documentToString(Document doc) throws MetsExportException {
    try {
        StringWriter sw = new StringWriter();
        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.transform(new DOMSource(doc), new StreamResult(sw));
        return sw.toString();
    } catch (TransformerException ex) {
        throw new MetsExportException("Error converting Document to String", false, ex);
    }
}

From source file:com.benchmark.TikaCLI.java

/**
 * Returns a transformer handler that serializes incoming SAX events
 * to XHTML or HTML (depending the given method) using the given output
 * encoding./*from  ww w .  j  a v  a2 s .  c om*/
 *
 * @see <a href="https://issues.apache.org/jira/browse/TIKA-277">TIKA-277</a>
 * @param output output stream
 * @param method "xml" or "html"
 * @param encoding output encoding,
 *                 or <code>null</code> for the platform default
 * @return {@link System#out} transformer handler
 * @throws TransformerConfigurationException
 *         if the transformer can not be created
 */
private static TransformerHandler getTransformerHandler(OutputStream output, String method, String encoding,
        boolean prettyPrint) throws TransformerConfigurationException {
    SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
    TransformerHandler handler = factory.newTransformerHandler();
    handler.getTransformer().setOutputProperty(OutputKeys.METHOD, method);
    handler.getTransformer().setOutputProperty(OutputKeys.INDENT, prettyPrint ? "yes" : "no");
    if (encoding != null) {
        handler.getTransformer().setOutputProperty(OutputKeys.ENCODING, encoding);
    }
    handler.setResult(new StreamResult(output));
    return handler;
}

From source file:com.ggvaidya.scinames.model.Project.java

public void saveToFile() throws IOException {
    File saveToFile = projectFile.getValue();

    if (saveToFile == null)
        throw new IOException("Project file not set: nowhere to save to!");

    /*//www .ja  v  a 2  s .c  o  m
    XMLOutputFactory factory = XMLOutputFactory.newFactory();
            
    try {
       XMLStreamWriter writer = factory.createXMLStreamWriter(new FileWriter(saveToFile));
               
       writer.writeStartDocument();
               
       serializeToXMLStream(writer);
               
       writer.writeEndDocument();
       writer.flush();
               
       // Success!
       lastModified.saved();
               
    } catch (XMLStreamException ex) {
       throw new IOException("Could not write project to XML file '" + saveToFile + "': " + ex);
    }*/

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    // Create a document representation of this project.
    Document docProject;
    try {
        DocumentBuilder db = dbf.newDocumentBuilder();
        docProject = db.newDocument();
        serializeToDocument(docProject);

    } catch (ParserConfigurationException ex) {
        Logger.getLogger(Project.class.getName()).log(Level.SEVERE, null, ex);
        return;
    }

    // Write the document representation of this project
    // as XML.
    TransformerFactory tfc = TransformerFactory.newInstance();
    try {
        OutputStream outputStream = new GZIPOutputStream(new FileOutputStream(saveToFile));
        StreamResult res = new StreamResult(outputStream);

        Transformer t = tfc.newTransformer();
        DOMSource ds = new DOMSource(docProject);

        t.setOutputProperty(OutputKeys.METHOD, "xml");
        t.setOutputProperty(OutputKeys.VERSION, "1.0"); // Do NOT change to 1.1 -- this leads to complex problems!
        t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        t.setOutputProperty(OutputKeys.STANDALONE, "yes");
        t.setOutputProperty(OutputKeys.INDENT, "yes");
        t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        t.transform(ds, res);

        // Success!
        lastModified.saved();
        outputStream.close();
    } catch (TransformerConfigurationException ex) {
        throw new IOException("Could not write out XML to '" + saveToFile + "': " + ex);
    } catch (TransformerException ex) {
        throw new IOException("Could not write out XML to '" + saveToFile + "': " + ex);
    }
}

From source file:jef.tools.XMLUtils.java

private static void output(Node node, StreamResult sr, String encoding, int indent, Boolean XmlDeclarion)
        throws IOException {
    if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
        sr.getWriter().write(node.getNodeValue());
        sr.getWriter().flush();/*from w  w  w. j  a v  a 2s  .co m*/
        return;
    }

    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = null;
    try {
        if (indent > 0) {
            try {
                tf.setAttribute("indent-number", indent);
                t = tf.newTransformer();
                // ?XML??XML?
                t.setOutputProperty(OutputKeys.INDENT, "yes");
            } catch (Exception e) {
            }
        } else {
            t = tf.newTransformer();
        }

        t.setOutputProperty(OutputKeys.METHOD, "xml");
        if (encoding != null) {
            t.setOutputProperty(OutputKeys.ENCODING, encoding);
        }
        if (XmlDeclarion == null) {
            XmlDeclarion = (node instanceof Document);
        }
        if (node instanceof Document) {
            Document doc = (Document) node;
            if (doc.getDoctype() != null) {
                t.setOutputProperty(javax.xml.transform.OutputKeys.DOCTYPE_PUBLIC,
                        doc.getDoctype().getPublicId());
                t.setOutputProperty(javax.xml.transform.OutputKeys.DOCTYPE_SYSTEM,
                        doc.getDoctype().getSystemId());
            }
        }
        if (XmlDeclarion) {
            t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        } else {
            t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        }
    } catch (Exception tce) {
        throw new IOException(tce);
    }
    DOMSource doms = new DOMSource(node);
    try {
        t.transform(doms, sr);
    } catch (TransformerException te) {
        IOException ioe = new IOException();
        ioe.initCause(te);
        throw ioe;
    }
}

From source file:com.haulmont.cuba.restapi.XMLConverter.java

protected String documentToString(Document document) {
    try {//from  w w  w.  ja v  a2 s. c om
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, StandardCharsets.UTF_8.name());
        transformer.setOutputProperty(OutputKeys.STANDALONE, "no");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.INDENT, "no");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

        StringWriter sw = new StringWriter();
        transformer.transform(new DOMSource(document), new StreamResult(sw));
        return sw.toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:de.betterform.xml.xforms.XFormsProcessorImpl.java

public void writeExternal(ObjectOutput objectOutput) throws IOException {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("serializing XFormsFormsProcessorImpl");
    }/* ww  w.  j  ava  2s. co  m*/
    try {
        if (getXForms().getDocumentElement().hasAttribute("bf:serialized")) {
            objectOutput.writeUTF(DOMUtil.serializeToString(getXForms()));
        } else {
            getXForms().getDocumentElement().setAttributeNS(NamespaceConstants.BETTERFORM_NS, "bf:baseURI",
                    getBaseURI());
            getXForms().getDocumentElement().setAttributeNS(NamespaceConstants.BETTERFORM_NS, "bf:serialized",
                    "true");

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("....::: XForms before writing ::::....");
                DOMUtil.prettyPrintDOM(getXForms());
            }

            DefaultSerializer serializer = new DefaultSerializer(this);
            Document serializedForm = serializer.serialize();

            StringWriter stringWriter = new StringWriter();
            Transformer transformer = null;
            StreamResult result = new StreamResult(stringWriter);
            try {
                transformer = TransformerFactory.newInstance().newTransformer();
                transformer.setOutputProperty(OutputKeys.METHOD, "xml");
                transformer.transform(new DOMSource(serializedForm), result);
            } catch (TransformerConfigurationException e) {
                throw new IOException("TransformerConfiguration invalid: " + e.getMessage());
            } catch (TransformerException e) {
                throw new IOException("Error during serialization transform: " + e.getMessage());
            }
            objectOutput.writeUTF(stringWriter.getBuffer().toString());
        }
    } catch (XFormsException e) {
        throw new IOException("baseURI couldn't be set");
    }

    objectOutput.flush();
    objectOutput.close();

}

From source file:org.castor.jaxb.CastorMarshallerTest.java

/**
 * Marshals the object into a {@link Node}.
 *
 * @param entity the object to marshall/*from  w w  w .  j  a v  a2 s .  c o  m*/
 *
 * @throws Exception if any error occurs during marshalling
 */
private void marshallNode(Object entity) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    Node document = builder.newDocument();

    marshaller.marshal(entity, document);

    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");

    StringWriter writer = new StringWriter();
    transformer.transform(new DOMSource(document), new StreamResult(writer));

    assertXMLEqual("Marshaller written invalid result.", EXPECTED_XML, writer.toString());
}

From source file:de.betterform.xml.dom.DOMUtil.java

/**
 * Serializes the specified node to the given stream. Serialization is achieved by an identity transform.
 *
 * @param node   the node to serialize//ww  w .  j av  a 2s  . c  om
 * @param stream the stream to serialize to.
 * @throws TransformerException if any error ccurred during the identity transform.
 */
public static void prettyPrintDOM(Node node, OutputStream stream) throws TransformerException {
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.transform(new DOMSource(node), new StreamResult(stream));
}

From source file:org.castor.jaxb.CastorMarshallerTest.java

/**
 * Marshals the object into a {@link DOMResult}.
 *
 * @param entity the object to marshall// w ww.  jav  a  2 s .  c  om
 *
 * @throws Exception if any error occurs during marshalling
 */
private void marshallDOMResult(Object entity) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    Node document = builder.newDocument();

    marshaller.marshal(entity, new DOMResult(document));

    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");

    StringWriter writer = new StringWriter();
    transformer.transform(new DOMSource(document), new StreamResult(writer));

    assertXMLEqual("Marshaller written invalid result.", EXPECTED_XML, writer.toString());
}

From source file:de.betterform.xml.dom.DOMUtil.java

public static void prettyPrintDOM(Node node, Node output) throws TransformerException {
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.transform(new DOMSource(node), new DOMResult(node));
}