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

public static String xmlToString(Document xml) {
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = null;

    try {//from  www .  j a v  a 2  s.c o m
        transformer = tFactory.newTransformer();
    } catch (TransformerConfigurationException e) {
        e.printStackTrace();
    }
    DOMSource source = new DOMSource(xml);
    StringWriter writer = new StringWriter();
    try {
        transformer.transform(source, new StreamResult(writer));
    } catch (TransformerException e) {
        e.printStackTrace();
    }
    return writer.toString();

}

From source file:Main.java

public static void hashMapToXML222(String xmlFile, String xpath, HashMap hashmap) {
    try {//from w w  w  .  j  a  v  a2 s  .co  m
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.newDocument();

        Element rootNode = document.createElement(xpath);
        document.appendChild(rootNode);

        Set set = hashmap.entrySet();
        Iterator i = set.iterator();

        while (i.hasNext()) {
            Map.Entry me = (Map.Entry) i.next();
            Element em = document.createElement(me.getKey().toString());
            em.appendChild(document.createTextNode(me.getValue().toString()));
            rootNode.appendChild(em);
            // System.out.println("write " +
            // me.getKey().toString() + "="
            // + me.getValue().toString());
        }

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(document);
        FileOutputStream fo = new FileOutputStream(xmlFile);
        StreamResult result = new StreamResult(fo);
        transformer.transform(source, result);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:Main.java

public static String getXMLStringFromDocument(Document doc) {
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = null;
    try {/*from  w w  w  .ja v a 2s.  c o m*/
        transformer = tf.newTransformer();
    } catch (TransformerConfigurationException e) {
        throw new RuntimeException(e);
    }
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    StringWriter writer = new StringWriter();
    try {
        transformer.transform(new DOMSource(doc), new StreamResult(writer));
    } catch (TransformerException e) {
        throw new RuntimeException("Error while transforming XML document to String : ", e);
    }
    String output = writer.getBuffer().toString();
    return output;
}

From source file:Main.java

/**
 * //from   ww w.j  ava 2  s. co m
 * <B>Purpose:</B>Converts an XML Document to a String Object
 * 
 * @param node
 * @return
 * @throws TransformerException
 */
public static String xmlToString(Node node) throws TransformerException {
    if (node == null) {
        return "";
    }
    Source source = new DOMSource(node);
    StringWriter stringWriter = new StringWriter();
    Result result = new StreamResult(stringWriter);
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    transformer.setOutputProperty("{http://xml.apache.org/xalan}line-separator", "\n");
    transformer.setOutputProperty("omit-xml-declaration", "yes");
    transformer.transform(source, result);
    return stringWriter.getBuffer().toString();
}

From source file:Main.java

/**
 * Writes the XML document to the particular file specified as argument
 * //from   w w  w .  j  av  a 2  s.c  o m
 * @param doc the document
 * @param filename the path to the file in which to write the XML data writing
 *            operation fails
 */
public static void writeXMLDocument(Document doc, String filename) {
    try {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer;
        transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File(filename));
        transformer.transform(source, result);
        log.fine("writing operation to " + filename + " successful!");
    } catch (TransformerConfigurationException e) {
        log.warning(e.getMessage());
    } catch (TransformerException e) {
        log.warning(e.getMessage());
    }
}

From source file:Main.java

static void emitDocument(Document doc, OutputStream os, String encoding) throws IOException {
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = null;//w ww  .  ja v  a  2  s. co m
    try {
        t = tf.newTransformer();
        //SF:no dtd            t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, PROPS_DTD_URI);
        t.setOutputProperty(OutputKeys.INDENT, "yes");
        t.setOutputProperty(OutputKeys.METHOD, "xml");
        t.setOutputProperty(OutputKeys.ENCODING, encoding);
    } catch (TransformerConfigurationException tce) {
        assert (false);
    }
    DOMSource doms = new DOMSource(doc);
    StreamResult sr = new StreamResult(os);
    try {
        t.transform(doms, sr);
    } catch (TransformerException te) {
        IOException ioe = new IOException();
        ioe.initCause(te);
        throw ioe;
    }
}

From source file:Main.java

/**
 * Store xml Signature represented by dom.Document into xml file
 * @param doc - XML Signature/*from  ww w . j  a va2s. co  m*/
 * @param fileName - name of output file
 */
public static boolean storeSignatureToXMLFile(Document doc, String fileName) {
    boolean stored = false;
    OutputStream os;
    File absolute = new File(fileName);

    String outputPath = new String();
    if (absolute.getParentFile().isAbsolute()) {
        outputPath = fileName; //path is absolute
    } else {
        outputPath = baseDir + File.separator + fileName; //relative, store it into %project_dir%/dist/signatures
    }

    File file = new File(outputPath);
    if (!file.getParentFile().exists()) {
        file.getParentFile().mkdirs();
    }

    try {
        os = new FileOutputStream(outputPath);

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer trans = tf.newTransformer();
        //trans.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        //trans.setOutputProperty(OutputKeys.INDENT, "no");
        //trans.setOutputProperty(OutputKeys.METHOD, "xml");

        trans.transform(new DOMSource(doc), new StreamResult(os));
        stored = true;
    } catch (FileNotFoundException e) {
        handleError(e);
    } catch (TransformerConfigurationException e) {
        handleError(e);
    } catch (TransformerException e) {
        handleError(e);
    }
    return stored;
}

From source file:Main.java

static void emitDocument(Document doc, OutputStream os, String encoding) throws IOException {
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = null;/*www .  j  ava2s .  com*/
    try {
        t = tf.newTransformer();
        t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, PROPS_DTD_URI);
        t.setOutputProperty(OutputKeys.INDENT, "yes");
        t.setOutputProperty(OutputKeys.METHOD, "xml");
        t.setOutputProperty(OutputKeys.ENCODING, encoding);
    } catch (TransformerConfigurationException tce) {
        assert (false);
    }
    DOMSource doms = new DOMSource(doc);
    StreamResult sr = new StreamResult(os);
    try {
        t.transform(doms, sr);
    } catch (TransformerException te) {
        IOException ioe = new IOException();
        ioe.initCause(te);
        throw ioe;
    }
}

From source file:Main.java

public static String getStringFromDocument(Document doc) {
    DOMSource domSource = new DOMSource(doc);
    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer;/*from  w  w w  .ja  v a  2s .c o  m*/
    try {
        transformer = tf.newTransformer();
        transformer.transform(domSource, result);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    return writer.toString();
}

From source file:Main.java

/**
 * Dump a {@link Document} or {@link Node}-compatible object to the given {@link OutputStream} (e.g. System.out).
 *
 * @param _docOrNode {@link Document} or {@link Node} object
 * @param _outStream {@link OutputStream} to print on
 * @throws IOException on error//from   w  ww.  ja  va2  s. c  o m
 */
public static void printDocument(Node _docOrNode, OutputStream _outStream) throws IOException {
    if (_docOrNode == null || _outStream == null) {
        throw new IOException("Cannot print (on) 'null' object");
    }

    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer;
    try {
        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(_docOrNode),
                new StreamResult(new OutputStreamWriter(_outStream, "UTF-8")));
    } catch (UnsupportedEncodingException | TransformerException _ex) {
        throw new IOException("Could not print Document or Node.", _ex);
    }

}