Example usage for javax.xml.transform TransformerFactory newInstance

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

Introduction

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

Prototype

public static TransformerFactory newInstance() throws TransformerFactoryConfigurationError 

Source Link

Document

Obtain a new instance of a TransformerFactory .

Usage

From source file:Main.java

public static String prettyPrint(Document doc) {
    TransformerFactory tfactory = TransformerFactory.newInstance();
    Transformer serializer;//from w  w  w  . j a va  2s . co  m
    StringWriter writer = new StringWriter();
    try {
        serializer = tfactory.newTransformer();
        //Setup indenting to "pretty print"
        serializer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
        serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); //$NON-NLS-1$ //$NON-NLS-2$

        serializer.transform(new DOMSource(doc), new StreamResult(writer));
        return writer.toString();
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    }
}

From source file:Main.java

public static void writeXmlFile(Document doc, String filename) {
    try {/*from www  .j  ava  2  s . co  m*/
        // Prepare the DOM document for writing
        Source source = new DOMSource(doc);

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

        // Write the DOM document to the file
        Transformer xformer = TransformerFactory.newInstance().newTransformer();
        xformer.transform(source, result);
    } catch (TransformerConfigurationException ex) {
        System.out.println(ex.getMessage());
    } catch (TransformerException ex) {
        System.out.println(ex.getMessage());
    }
}

From source file:Main.java

private static String nodeToString(Node node) throws Exception {
    StringWriter sw = new StringWriter();
    Transformer t = TransformerFactory.newInstance().newTransformer();
    t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    t.setOutputProperty(OutputKeys.INDENT, "yes");
    t.transform(new DOMSource(node), new StreamResult(sw));
    return sw.toString();
}

From source file:Main.java

public static String formatXML(String unformatted)
        throws SAXException, IOException, TransformerException, ParserConfigurationException {

    if (unformatted == null)
        return null;

    // remove whitespaces between xml tags
    String unformattedNoWhiteSpaces = unformatted.toString().replaceAll(">[\\s]+<", "><");

    // Instantiate transformer input
    Source xmlInput = new StreamSource(new StringReader(unformattedNoWhiteSpaces));
    StreamResult xmlOutput = new StreamResult(new StringWriter());

    // Configure transformer
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

    transformer.transform(xmlInput, xmlOutput);
    String formatted = xmlOutput.getWriter().toString();

    return formatted;
}

From source file:Main.java

public static void saveDoc(Document doc, String fileName) {
    try {//from   w  ww. j  a  va 2s.  c  o m
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);

        StreamResult result = new StreamResult(new File(fileName));
        transformer.transform(source, result);
    } catch (TransformerException e) {
        e.printStackTrace();
    }
}

From source file:Util.java

/**
 * Applies a stylesheet to a given xml document.
 * //  w  w  w  . j a  va 2s  . c  o 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

/**
 * Uses a TransformerFactory with an identity transformation to convert a
 * Document into a String representation of the XML.
 *
 * @param document Document.//w w  w.java  2  s.c om
 * @return An XML String.
 * @throws IOException if an error occurs during transformation.
 */
public static String documentToString(Document document) throws IOException {
    String xml = null;

    try {
        DOMSource dom = new DOMSource(document);
        StringWriter writer = new StringWriter();
        StreamResult output = new StreamResult(writer);

        // Use Transformer to serialize a DOM
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();

        // No need for pretty printing
        transformer.setOutputProperty(OutputKeys.INDENT, INDENT_XML);

        // XML Declarations unexpected whitespace for legacy AS XMLDocument type,
        // so we always omit it. We can't tell whether one was present when
        // constructing the Document in the first place anyway...
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, OMIT_XML_DECLARATION);

        transformer.transform(dom, output);

        xml = writer.toString();
    } catch (TransformerException te) {
        throw new IOException("Error serializing Document as String: " + te.getMessageAndLocation());
    }
    return xml;
}

From source file:Main.java

public static void printNode(Node node, String fn) {
    try {//from  www .  ja  v  a  2 s . co  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

/**
 * Convert xml to string./*from  w  w  w  . ja v  a2 s. c  o  m*/
 *
 * @param pDocument
 *            the p document
 * @param encoding
 *            the encoding
 * @return the string
 * @throws Exception
 *             the exception
 */
public static String convertXML2String(Document pDocument, String encoding) throws Exception {
    TransformerFactory transformerFactory = null;
    Transformer transformer = null;
    DOMSource domSource = null;
    StringWriter writer = new java.io.StringWriter();
    StreamResult result = null;

    try {
        transformerFactory = TransformerFactory.newInstance();
        if (transformerFactory == null) {
            throw new Exception("TransformerFactory error");
        }

        transformer = transformerFactory.newTransformer();
        if (transformer == null) {
            throw new Exception("Transformer error");
        }

        if (encoding != null) {
            transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
        } else {
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        }

        domSource = new DOMSource(pDocument);
        result = new StreamResult(writer);

        transformer.transform(domSource, result);

        return writer.toString();
    } catch (TransformerFactoryConfigurationError e) {
        throw new Exception("TransformerFactoryConfigurationError", e);
    } catch (TransformerConfigurationException e) {
        throw new Exception("TransformerConfigurationException", e);
    } catch (TransformerException e) {
        throw new Exception("TransformerException", e);
    } finally {
        try {
            if (writer != null) {
                writer.close();
            }
        } catch (IOException ex) {
            throw new Exception("IO error", ex);
        }
    }
}

From source file:Main.java

/**
 * Writes  XML Document into an xml file.
 * //from   w  w w.j  a v a2  s. c om
 * @param fileName  the target file with the full path
 * @param document   the source document
 * @return   boolean true if the file saved
 * @throws Exception
 */
public static boolean writeXmlFile(String fileName, Document document) throws Exception {

    // creating and writing to xml file  

    File file = new File(fileName);

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); // to prevent XML External Entities attack

    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    transformer.transform(new DOMSource(document), new StreamResult(file));

    return true;

}