Example usage for javax.xml.transform Transformer transform

List of usage examples for javax.xml.transform Transformer transform

Introduction

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

Prototype

public abstract void transform(Source xmlSource, Result outputTarget) throws TransformerException;

Source Link

Document

Transform the XML Source to a Result.

Usage

From source file:Main.java

public static String xmltoString(final Document document) throws TransformerException {
    StringWriter stringWriter = new StringWriter();
    StreamResult streamResult = new StreamResult(stringWriter);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.transform(new DOMSource(document.getDocumentElement()), streamResult);
    return stringWriter.toString();
}

From source file:Main.java

public static String xmlToString(Document doc) {
    try {/*from  www . j  a  v a  2  s . c om*/
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        StreamResult result = new StreamResult(new StringWriter());
        DOMSource source = new DOMSource(doc);
        transformer.transform(source, result);
        return result.getWriter().toString();
    } catch (TransformerException ex) {
        System.err.println("Error: Cannot load xml transformer");
        System.err.println("Cause: " + ex.toString());
        System.exit(1);
        return null;
    }
}

From source file:Main.java

public static void writeXmlFile(Document doc, File file, boolean indent, String encoding)
        throws TransformerFactoryConfigurationError, TransformerException {
    // Prepare the DOM document for writing
    Source source = new DOMSource(doc);

    // Prepare the output file
    Result result = new StreamResult(file);

    Transformer xformer = TransformerFactory.newInstance().newTransformer();

    xformer.setOutputProperty(OutputKeys.ENCODING, encoding);

    if (indent) {
        xformer.setOutputProperty(OutputKeys.INDENT, "yes");
    }//  w ww .  jav a 2s. co  m

    xformer.transform(source, result);

}

From source file:Main.java

/**
 * Output an XML document to the given file.
 * /*ww w  . j a v a 2s . c  o m*/
 * @param doc XML document to write.
 * @param filename File to write to.
 */
public static void writeXmlDocument(Document doc, String filename) {
    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        DOMSource source = new DOMSource(doc);
        final FileOutputStream out = new FileOutputStream(new File(filename));
        StreamResult result = new StreamResult(out);
        transformer.transform(source, result);
        out.close();
    } catch (IOException e) {
        LOGGER.warning("Error closing stream or could open a file from writing an XML document.");
        e.printStackTrace();
    } catch (TransformerConfigurationException e) {
        LOGGER.warning("TransformerConfigurationException thrown when writing XML document to a file.");
        e.printStackTrace();
    } catch (TransformerException e) {
        LOGGER.warning("Transformer exception thrown when writing XML document to a file.");
        e.printStackTrace();
    }
}

From source file:Util.java

/**
 * Applies a stylesheet to a given xml document.
 * /*w w w  .jav a  2  s . co m*/
 * @param xmlDocument
 *            the xml document to be transformed
 * @param xsltFilename
 *            the filename of the stylesheet
 * @return the transformed xml document
 * @throws Exception
 */
public static String transformDocumentAsString(Document xmlDocument, String xsltFilename) throws Exception {
    // Generate a Transformer.
    Transformer transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(xsltFilename));

    StringWriter stringWriter = new StringWriter();
    StreamResult streamResult = new StreamResult(stringWriter);

    // Perform the transformation.
    transformer.transform(new DOMSource(xmlDocument), streamResult);
    // Now you can get the output Node from the DOMResult.
    return stringWriter.toString();
}

From source file:Main.java

static void serialize(Document document, Writer writer) {
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    transformerFactory.setAttribute("indent-number", new Integer(4));
    try {/*www . j a  va2 s  .c o m*/
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        StreamResult result = new StreamResult(writer);
        transformer.transform(new DOMSource(document), result);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:Main.java

public static String XMLtoString(Document doc) throws Exception {
    try {//from  ww w  .  j  a  v a  2  s.  c o m
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer;
        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));
        return writer.getBuffer().toString();
    } catch (TransformerException te) {
        throw new Exception(te.getMessageAndLocation());
    }
}

From source file:ru.retbansk.utils.UsefulMethods.java

/**
 * For testing usage. Take unformatted xml string. Return pretty readable xml string
 * //  ww  w  .ja  v a 2  s.  co  m
 * @param input take unformatted xml string
 * @param indent a number of white spaces before each line
 * @return pretty readable xml string
 */

public static String prettyFormat(String input, int indent) {
    try {
        Source xmlInput = new StreamSource(new StringReader(input));
        StringWriter stringWriter = new StringWriter();
        StreamResult xmlOutput = new StreamResult(stringWriter);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        // This statement works with JDK 6
        transformerFactory.setAttribute("indent-number", indent);

        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(xmlInput, xmlOutput);
        return xmlOutput.getWriter().toString();
    } catch (Throwable e) {
        // You'll come here if you are using JDK 1.5
        // you are getting an the following exeption
        // java.lang.IllegalArgumentException: Not supported: indent-number
        // Use this code (Set the output property in transformer.
        try {
            Source xmlInput = new StreamSource(new StringReader(input));
            StringWriter stringWriter = new StringWriter();
            StreamResult xmlOutput = new StreamResult(stringWriter);
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(indent));
            transformer.transform(xmlInput, xmlOutput);
            return xmlOutput.getWriter().toString();
        } catch (Throwable t) {
            return input;
        }
    }
}

From source file:edu.unc.lib.dl.util.SOAPUtil.java

private static void print(SOAPMessage msg, StreamResult result) {
    try {/*w  ww  .  j av  a  2s  .  c  o m*/
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        Source sourceContent = msg.getSOAPPart().getContent();
        //StreamResult result = new StreamResult(out);
        transformer.transform(sourceContent, result);
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    } catch (SOAPException e) {
        throw new RuntimeException(e);
    }
}

From source file:Main.java

/**
 * Writes the given document to the given writer.
 *
 * @param document the document to write
 * @param writer receives the written document
 * @param indent number of spaces to indent, null means don't indent
 *//*from w w  w .  j  av  a 2 s  .  com*/
public static void writeDocument(Document document, Writer writer, Integer indent) {
    TransformerFactory tf = TransformerFactory.newInstance();
    try {
        Transformer trans = tf.newTransformer();
        if (indent != null) {
            trans.setOutputProperty(OutputKeys.INDENT, "yes");
            trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(indent));
        }
        trans.transform(new DOMSource(document), new StreamResult(writer));
    } catch (TransformerConfigurationException e) {
        throw new RuntimeException(e);
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    }
}