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

static void serialize(Document document, Writer writer) {
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    transformerFactory.setAttribute("indent-number", new Integer(4));
    try {//  w w w .j a  va2  s.  c om
        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 Transformer newTransformer(boolean indented) {

    String indentFlag = (indented) ? "yes" : "no";

    try {/*from  www.j  a  v a2 s  .c  o  m*/

        TransformerFactory factory = TransformerFactory.newInstance();
        factory.setAttribute("indent-number", DEFAULT_INDENT);

        Transformer transformer;
        transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.INDENT, indentFlag);
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");

        return transformer;

    } catch (TransformerConfigurationException e) {
        throw new RuntimeException(e);
    }
}

From source file:de.tudarmstadt.ukp.shibhttpclient.Utils.java

public static String xmlToString(XMLObject aObject) throws IOException {
    Document doc;//from  ww w.j a  va2s .co m
    try {
        doc = Configuration.getMarshallerFactory().getMarshaller(aObject).marshall(aObject).getOwnerDocument();
    } catch (MarshallingException e) {
        throw new IOException(e);
    }

    try {
        Source source = new DOMSource(doc);
        StringWriter stringWriter = new StringWriter();
        Result result = new StreamResult(stringWriter);
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();
        transformer.transform(source, result);
        return stringWriter.getBuffer().toString();
    } catch (TransformerException e) {
        throw new IOException(e);
    }
}

From source file:Main.java

public static String tryFormattingString(String s) {
    try {/* w  ww .ja  va  2 s .c o m*/
        ByteArrayInputStream in = new ByteArrayInputStream(s.getBytes());
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setErrorHandler(new ErrorHandler() {

            @Override
            public void warning(SAXParseException exception) throws SAXException {
            }

            @Override
            public void fatalError(SAXParseException exception) throws SAXException {
            }

            @Override
            public void error(SAXParseException exception) throws SAXException {
            }
        });
        Document doc = builder.parse(in);
        TransformerFactory tf = TransformerFactory.newInstance();
        // tf.setAttribute("indent-number", new Integer(2));
        Transformer trans = tf.newTransformer();
        DOMSource source = new DOMSource(doc);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        StreamResult result = new StreamResult(out);
        trans.setOutputProperty(OutputKeys.INDENT, "yes");
        trans.setOutputProperty(OutputKeys.METHOD, "xml");
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

        trans.transform(source, result);
        return out.toString();

    } catch (Exception e) {
        // Console.println("Could not validate the soapmessage, although I'll show it anyway..");
    }
    return s;
}

From source file:Main.java

/**
 * Method to get formatted Xml string from Xml source
 *
 * @param payload Source//ww w  . j  a v  a  2 s .co  m
 * @return a formatted Xml string
 */
public static String getXmlStringFromSource(Source payload) {
    String result = null;
    StreamResult strResult = new StreamResult(new StringWriter());

    if (payload != null) {
        try {
            TransformerFactory factory = TransformerFactory.newInstance();
            //factory.setAttribute("indent-number", new Integer(2));
            Transformer transformer = factory.newTransformer();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            transformer.setOutputProperty(OutputKeys.METHOD, "xml");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "1");
            transformer.transform(payload, strResult);
        } catch (TransformerException e) {
            e.printStackTrace();
        }
        result = strResult.getWriter().toString();
    }
    return result;
}

From source file:Main.java

/**
 * @param doc//w ww .j av a2s.  c o m
 * @return
 * @throws RuntimeException
 */
public static String prettyPrint(Document doc) throws RuntimeException {
    TransformerFactory tfactory = TransformerFactory.newInstance();
    Transformer serializer;
    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

/**
 *  write the dom content into xml file/*www.j a  va2s .  co m*/
 * @param indent
 * @param n
 */
public static void writeDOM2XMLFile(Document domDoc, String fileName) {
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = null;
    try {
        transformer = transformerFactory.newTransformer();
    } catch (TransformerConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    // no effect ?
    //      transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    //      transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
    //      transformer.setOutputProperty(OutputKeys.STANDALONE , "yes");
    //      transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    DOMSource source = new DOMSource(domDoc);
    StreamResult result = new StreamResult(new File(fileName));

    // Output to console for testing
    // StreamResult result = new StreamResult(System.out);

    try {
        transformer.transform(source, result);
    } catch (TransformerException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    System.err.println("Info: dom document saved in file, " + fileName + " !");
}

From source file:Main.java

/**
 * Converts an XML node (or document) to an XML String.
 *
 * @param node/*w w w . jav a  2  s.c o  m*/
 * @return
 * @throws TransformerException
 */
public static String toString(Node node) throws TransformerException {

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();

    // Node source
    DOMSource source = new DOMSource(node);

    // StringWriter result
    StringWriter stringWriter = new StringWriter();
    Result result = new StreamResult(stringWriter);

    transformer.transform(source, result);
    return stringWriter.toString();
}

From source file:Main.java

/**
 * Formatte un XML/*from   w  w w.j  av  a 2s . c om*/
 * */
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();
        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) {
        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:Main.java

public static void saveDomSource(final DOMSource source, final File target, final File xslt)
        throws TransformerException, IOException {
    TransformerFactory transFact = TransformerFactory.newInstance();
    transFact.setAttribute("indent-number", 2);
    Transformer trans;/*  w w  w  .j  av a  2s .c  om*/
    if (xslt == null) {
        trans = transFact.newTransformer();
    } else {
        trans = transFact.newTransformer(new StreamSource(xslt));
    }
    trans.setOutputProperty(OutputKeys.INDENT, "yes");
    FileOutputStream fos = new FileOutputStream(target);
    trans.transform(source, new StreamResult(new OutputStreamWriter(fos, "UTF-8")));
    fos.close();
}