Example usage for javax.xml.transform TransformerFactory newTransformer

List of usage examples for javax.xml.transform TransformerFactory newTransformer

Introduction

In this page you can find the example usage for javax.xml.transform TransformerFactory newTransformer.

Prototype

public abstract Transformer newTransformer() throws TransformerConfigurationException;

Source Link

Document

Create a new Transformer that performs a copy of the Source to the Result .

Usage

From source file:Main.java

/**
 * Converts a DOM Tree to a String./*from   ww w  .ja v a2 s  .c om*/
 *
 * @param xml The DOM document to convert.
 *
 * @return A string containing the XML if successful, null otherwise.
 */
public static String xmlToString(Document xml) {
    try {
        TransformerFactory f = TransformerFactory.newInstance();
        StringWriter writer = new StringWriter();
        Transformer t = f.newTransformer();
        DOMSource src = new DOMSource(xml);
        StreamResult result = new StreamResult(writer);
        t.transform(src, result);
        return writer.toString();
    } catch (TransformerException e) {
        return null;
    }
}

From source file:Main.java

/**
 * src:http://www.journaldev.com/1237/java-convert-string-to-xml-document-and-xml-document-to-string
 * @param doc/*from w w w. j  a  v  a 2s.c om*/
 * @return
 */
public static String convertDocumentToString(Document doc) {
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer;
    try {
        transformer = tf.newTransformer();
        // below code to remove XML declaration
        // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        StringWriter writer = new StringWriter();
        transformer.transform(new DOMSource(doc), new StreamResult(writer));
        String output = writer.getBuffer().toString();
        return output;
    } catch (TransformerException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:Main.java

public static void writeDocument(Document doc, OutputStream os) throws IOException {
    try {//from   w w w  .  j  ava  2  s. co m
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", "2");

        DOMSource source = new DOMSource(doc);
        CharsetEncoder utf8Encoder = Charset.forName("UTF-8").newEncoder();
        StreamResult result = new StreamResult(new OutputStreamWriter(os, utf8Encoder));
        transformer.transform(source, result);
    } catch (TransformerException e) {
        System.err.println(e.getMessage());
    }
}

From source file:Main.java

public static void writeTo(Document document, File output) {
    try {/*from   w ww. j a va 2 s .  com*/
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(document);

        FileOutputStream outputstream = new FileOutputStream(output);
        StreamResult result = new StreamResult(outputstream);

        // Manually add xml declaration, to force a newline after it.
        String xmlDeclaration = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
        outputstream.write(xmlDeclaration.getBytes());

        // Remove whitespaces outside tags.
        // Essential to make sure the nodes are properly indented.
        XPath xPath = XPathFactory.newInstance().newXPath();
        NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']", document,
                XPathConstants.NODESET);
        for (int i = 0; i < nodeList.getLength(); ++i) {
            Node node = nodeList.item(i);
            node.getParentNode().removeChild(node);
        }

        // Pretty-print options.
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        transformer.transform(source, result);

        outputstream.close();
    } catch (TransformerException | IOException | XPathExpressionException e) {
        System.out.println("Failed to write document file" + output.getPath() + ": " + e.toString());
    }
}

From source file:Main.java

public static synchronized void deserialize(InputStream source, Result result)
        throws TransformerConfigurationException, JAXBException, TransformerException {
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer;/*from www. j  a  va 2 s .  co  m*/
    transformer = factory.newTransformer();
    transformer.transform(new StreamSource(source), result);
}

From source file:Main.java

public static String XMLToString(Document doc, Boolean singleLine) {
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = null;
    try {//from   w ww  . j av a2  s. c  o  m
        transformer = tf.newTransformer();
    } catch (TransformerConfigurationException e) {
        e.printStackTrace();
    }
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    StringWriter writer = new StringWriter();
    try {
        transformer.transform(new DOMSource(doc), new StreamResult(writer));
    } catch (TransformerException e) {
        e.printStackTrace();
    }
    String string = writer.getBuffer().toString();
    if (!singleLine) {
        return string;
    }
    return string.replaceAll("\n|\r", "");

}

From source file:Main.java

public static void printNode(Node node, String fn) {
    try {/*from  ww  w. jav  a2 s  .c  o  m*/
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer;
        transformer = tFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        DOMSource source = new DOMSource(node);
        PrintStream out = System.out;
        if (fn != null)
            out = new PrintStream(new FileOutputStream(fn));
        StreamResult result = new StreamResult(out);
        transformer.transform(source, result);
        out.close();
    } catch (TransformerConfigurationException e) {
        e.printStackTrace();
    } catch (TransformerException e) {

        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

From source file:Main.java

/** set up transformer to output a standalone "fragment" - suppressing xml declaration
 * @param tf see {@link #transformerFactory()}
 * @return Transformer that is fully set up
 *///from  w ww.  j  ava 2  s . c  o  m
public static Transformer newFragmentTransformer(final TransformerFactory tf)
        throws TransformerConfigurationException {
    final Transformer transformer = tf.newTransformer();
    setUtfEncoding(transformer);
    setIndentFlag(transformer);
    setTransformerIndent(transformer);
    outputStandaloneFragment(transformer);
    return transformer;
}

From source file:Main.java

/**
 * @param dom/*from   w ww .  j a  va 2 s .c  o m*/
 * @param outFile
 */
public static void writeDomToFile(Element dom, File outFile) {
    try {
        TransformerFactory transFact = TransformerFactory.newInstance();
        Transformer transformer = transFact.newTransformer();
        DOMSource source = new DOMSource(dom);
        StreamResult result;

        result = new StreamResult(
                new OutputStreamWriter(new FileOutputStream(outFile), System.getProperty("file.encoding")));
        transformer.transform(source, result);
    } catch (Exception e) {
        throw new RuntimeException(
                "Could not write dom tree '" + dom.getBaseURI() + "' to file '" + outFile.getName() + "'!", e);
    }
}

From source file:Main.java

public static void writeDoc(Document doc, File file) throws Exception {
    TransformerFactory transformerFactory = SAXTransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    // transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    // transformer.setOutputProperty(
    // "{http://xml.apache.org/xslt}indent-amount", "2");

    // XPathFactory xpathFactory = XPathFactory.newInstance();
    // // XPath to find empty text nodes.
    // XPathExpression xpathExp =
    // xpathFactory.newXPath().compile(
    // "//text()[normalize-space(.) = '']");
    // NodeList emptyTextNodes =
    // (NodeList) xpathExp.evaluate(doc, XPathConstants.NODESET);
    ///*ww  w .ja v a  2s . c  o  m*/
    // // Remove each empty text node from document.
    // for (int i = 0; i < emptyTextNodes.getLength(); i++) {
    // Node emptyTextNode = emptyTextNodes.item(i);
    // emptyTextNode.getParentNode().removeChild(emptyTextNode);
    // }

    DOMSource source = new DOMSource(doc);

    StreamResult result = new StreamResult(file);
    transformer.transform(source, result);
}