Example usage for javax.xml.transform Transformer setOutputProperty

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

Introduction

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

Prototype

public abstract void setOutputProperty(String name, String value) throws IllegalArgumentException;

Source Link

Document

Set an output property that will be in effect for the transformation.

Usage

From source file:io.leishvl.core.xml.XmlHelper.java

/**
 * Obtains a String representation of a XML document, omitting the XML declaration.
 * @param document the document to be transformed into String.
 * @return a String representation of the specified XML document.
 *//*ww  w  .  j  a  v  a2s. c o m*/
public static String documentToStringOmitXmlDeclaration(final Document document) {
    checkNotNull(document, "Uninitialized document");
    String docStr;
    try {
        final TransformerFactory tf = TransformerFactory.newInstance();
        final Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(ENCODING, UTF_8.name());
        transformer.setOutputProperty(OMIT_XML_DECLARATION, "yes");
        final StringWriter writer = new StringWriter();
        transformer.transform(new DOMSource(document), new StreamResult(writer));
        docStr = writer.toString();
    } catch (Exception e) {
        docStr = null;
        LOGGER.warn("Failed to convert DOM document to String", e);
    }
    return docStr;
}

From source file:io.leishvl.core.xml.XmlHelper.java

public static String prettyPrint(final Document document) {
    checkNotNull(document, "Uninitialized document");
    String docStr;/*w  ww  .ja  va2s. com*/
    try {
        final TransformerFactory tf = TransformerFactory.newInstance();
        final Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(ENCODING, UTF_8.name());
        transformer.setOutputProperty(OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(INDENT, "yes");
        final StringWriter writer = new StringWriter();
        transformer.transform(new DOMSource(document), new StreamResult(writer));
        docStr = writer.toString();
    } catch (Exception e) {
        docStr = null;
        LOGGER.warn("Failed to convert DOM document to String", e);
    }
    return docStr;
}

From source file:Main.java

public static void saveDocument(Document doc, File transform, File file) throws IOException {
    try {/*from   w  ww.  j  a  va2 s. c o  m*/
        TransformerFactory tFactory = TransformerFactory.newInstance();
        tFactory.setAttribute("indent-number", new Integer(2));
        Transformer transformer = tFactory.newTransformer(new StreamSource(transform));
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        FileOutputStream fos = new FileOutputStream(file.getPath());

        DOMSource source = new DOMSource(doc);
        CharsetEncoder utf8Encoder = Charset.forName("UTF-8").newEncoder();
        StreamResult result = new StreamResult(new OutputStreamWriter(fos, utf8Encoder));

        transformer.transform(source, result);
        fos.close();
    } catch (TransformerException e) {
        throw new IOException(e);
    }
}

From source file:Main.java

public static void serialize(Document doc, OutputStream out) throws Exception {

    TransformerFactory tfactory = TransformerFactory.newInstance();
    Transformer serializer;
    try {/*from w ww  .  ja  va 2  s .  co  m*/
        serializer = tfactory.newTransformer();
        //Setup indenting to "pretty print"
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

        serializer.transform(new DOMSource(doc), new StreamResult(out));
    } catch (TransformerException e) {
        // this is fatal, just dump the stack and throw a runtime exception
        e.printStackTrace();

        throw new RuntimeException(e);
    }
}

From source file:Main.java

public static String sourceToXMLString(Source result) {

    String xmlResult = null;/*  w  ww  . j a va  2  s .  co m*/
    try {
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();
        //transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        StringWriter out = new StringWriter();
        StreamResult streamResult = new StreamResult(out);
        transformer.transform(result, streamResult);
        xmlResult = streamResult.getWriter().toString();
    } catch (TransformerException e) {
        e.printStackTrace();
    }

    return xmlResult;
}

From source file:Main.java

public static void exportXmlFile(ArrayList<?> listObject, String rootElement, String interfaceName,
        String pathSaveFile) {//w  w  w .  j av  a2s .co  m
    try {
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();
        // creating a new instance of a DOM to build a DOM tree.
        Document doc = docBuilder.newDocument();

        Element root = doc.createElement(rootElement);
        // adding a node after the last child node of the specified node.
        doc.appendChild(root);

        Element interfaceElement = null;

        Element child = null;
        Text text;

        for (Object obj : listObject) {
            Class srcClass = obj.getClass();
            Field[] field = srcClass.getFields();
            interfaceElement = doc.createElement(interfaceName);
            for (int i = 0; i < field.length; i++) {
                // System.out.println(field[i].getName() + ":" +
                // field[i].get(obj));
                child = doc.createElement(field[i].getName());

                text = doc.createTextNode((field[i].get(obj)).toString());
                child.appendChild(text);

                interfaceElement.appendChild(child);
            }
            root.appendChild(interfaceElement);
        }

        // TransformerFactory instance is used to create Transformer
        // objects.
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();

        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        // create string from xml tree
        StringWriter sw = new StringWriter();
        StreamResult result = new StreamResult(sw);
        DOMSource source = new DOMSource(doc);
        transformer.transform(source, result);
        String xmlString = sw.toString();

        File file = new File(pathSaveFile);
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
        bw.write(xmlString);
        bw.flush();
        bw.close();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

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

public static String xmlToString(Element doc) {
    StringWriter sw = new StringWriter();
    try {/* w  w  w.  java 2 s .co m*/
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer 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(doc), new StreamResult(sw));
        return sw.toString();
    } catch (TransformerException e) {
        LOG.error("Unable to print message contents: ", e);
        return "<ERROR: " + e.getMessage() + ">";
    }
}

From source file:Main.java

/**
 * Return the contents of the node as a string. Any exceptions are ignored and the method returns null.
 * //from   w ww .j a  va  2 s .c o  m
 * @param node
 * @param indent
 *            Indent the XML when formatting
 * @return The node contents
 */
public static String getString(Node node, boolean indent) {
    Transformer transformer;
    try {
        transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, (indent) ? "yes" : "no");

        StreamResult result = new StreamResult(new StringWriter());
        DOMSource source = new DOMSource(node);
        transformer.transform(source, result);

        return result.getWriter().toString();
    } catch (TransformerConfigurationException e) {
        //e.printStackTrace();
    } catch (TransformerFactoryConfigurationError e) {
        //e.printStackTrace();
    } catch (TransformerException e) {
        //e.printStackTrace();
    }
    return "";
}

From source file:Main.java

private static void finalizeXML(File xmlFile, Document doc, int intendAmount) throws Exception {
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(xmlFile);
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "" + intendAmount);
    transformer.setOutputProperty("indent", "yes");
    transformer.transform(source, result);
}

From source file:Main.java

public static boolean write(String filename, Document document, boolean addDocType) {
    try {//from w w w  .j  a va 2  s .c  o  m
        TransformerFactory tf = TransformerFactory.newInstance();
        tf.setAttribute("indent-number", new Integer(4));
        Transformer transformer = tf.newTransformer();
        DOMSource source = new DOMSource(document);
        if (addDocType) {
            transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,
                    "-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN");
            transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,
                    "http://java.sun.com/dtd/facelet-taglib_1_0.dtd");
        }
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(source,
                new StreamResult(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename)))));
        return true;
    } catch (Exception e) {
        return false;
    }

}