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 void pretty(Document document, OutputStream outputStream, int indent) throws IOException {
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = null;
    try {/*from w  w w .ja v a  2s.c  om*/
        transformer = transformerFactory.newTransformer();
    } catch (TransformerConfigurationException e) {
        throw new RuntimeException(e);
    }
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    if (indent > 0) {
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", Integer.toString(indent));
    }
    Result result = new StreamResult(outputStream);
    Source source = new DOMSource(document);
    try {
        transformer.transform(source, result);
    } catch (TransformerException e) {
        throw new IOException(e);
    }
}

From source file:Main.java

/**
 * Writes a DOM document in a file with XML format
 * /* w w w  .ja  va2  s.c  om*/
 * @param doc
 *            The document to write
 * @param file
 *            The name of the output file
 * 
 * @throws FileNotFoundException
 *             java.io.FileNotFoundException
 * @throws TransformerException
 *             javax.xml.transform.TransformerException
 */
public static void write_DOM_into_an_XML_file(Document doc, String file)
        throws FileNotFoundException, TransformerException {
    // An instance of a object transformer factory to create 'transformer'
    // objects
    TransformerFactory transFactory = TransformerFactory.newInstance();
    Transformer transformer = transFactory.newTransformer();

    // Holds a tree with the information of a document in the form of a DOM
    // tree
    DOMSource source = new DOMSource(doc);

    /*
     * Creates a StreamResult object associated to a file, transforms the
     * document tree to XML and stores it in a file
     */
    // Creates the output file
    File newXML = new File(file);

    // Associates the file to a file output stream
    FileOutputStream os = new FileOutputStream(newXML);

    // Associates that stream as 'stream result' object
    StreamResult result = new StreamResult(os);

    // Makes the stream transformation from the source to the result
    transformer.transform(source, result);
}

From source file:Main.java

/** Write an XML DOM tree to a file
 *
 * @param doc the document to write/*  w  ww  .ja  v  a2s  . c o  m*/
 * @param file the file to write to
 * @throws IOException if a file I/O error occurs
 */
public static void write(Document doc, File file) throws IOException {
    try {
        DOMSource domSource = new DOMSource(doc);
        FileOutputStream stream = new FileOutputStream(file);
        // OutputStreamWriter works around indent bug 6296446 in JDK
        // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6296446
        StreamResult streamResult = new StreamResult(new OutputStreamWriter(stream));
        TransformerFactory tf = TransformerFactory.newInstance();
        tf.setAttribute("indent-number", new Integer(2));
        Transformer serializer = tf.newTransformer();
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.transform(domSource, streamResult);
    } catch (TransformerException e) {
        // This exception is never thrown, treat as fatal if it is
        throw new RuntimeException(e);
    }
}

From source file:Main.java

private static void write(Document doc) {
    try {//from w w w .  jav a  2  s .c om
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer;
        transformer = tFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File("hooks.xml"));
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "5");
        transformer.transform(source, result);
    } catch (TransformerException e) {
        e.printStackTrace();
    }
}

From source file:Main.java

/**
 * Writes a {@link Document} as text to the given {@link Writer}.
 * @param doc the document to output/*from   www  . j a  v a2 s .  com*/
 * @param out the writer to output to
 */
public static void writeDocument(Document doc, Writer out) {
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = null;
    try {
        transformer = transformerFactory.newTransformer();
    } catch (final TransformerConfigurationException e) {
        throw new RuntimeException(e); // TODO proper exception handling
    }
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(out);

    try {
        transformer.transform(source, result);
    } catch (final TransformerException e) {
        throw new RuntimeException(e); // TODO proper exception handling
    }
}

From source file:Main.java

public static String xmlParaString(Node doc) {
    DOMSource xmlSource = new DOMSource(doc);

    StringWriter sw = new StringWriter();
    Result result = new StreamResult(sw);

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer;//ww  w. ja v a  2  s.c  o  m

    try {
        transformer = transformerFactory.newTransformer();
    } catch (TransformerConfigurationException e) {
        throw new RuntimeException(e);
    }

    try {
        transformer.transform(xmlSource, result);
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    }
    return sw.toString();
}

From source file:Main.java

public static String setAttribute(String xmlStr, String tagName, String attrName, String newValue) {
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(false); // never forget this!
    int i, j;//from  ww  w.java 2  s.  co m
    Document doc = null;
    DocumentBuilder builder = null;

    StringWriter stringOut = new StringWriter();
    try {
        builder = domFactory.newDocumentBuilder();
        doc = builder.parse(new ByteArrayInputStream(xmlStr.getBytes()));
        // Get the root element
        Node rootNode = doc.getFirstChild();
        NodeList nodeList = doc.getElementsByTagName(tagName);
        if ((nodeList.getLength() == 0) || (nodeList.item(0).getAttributes().getNamedItem(attrName) == null)) {
            logger.error("Either node " + tagName + " or attribute " + attrName + " not found.");
        } else {
            logger.debug("value of " + tagName + " attribute: " + attrName + " = "
                    + nodeList.item(0).getAttributes().getNamedItem(attrName).getNodeValue());
            nodeList.item(0).getAttributes().getNamedItem(attrName).setNodeValue(newValue);

            // write the content into xml file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(stringOut);
            // StreamResult result = new StreamResult(new File(filepath));
            transformer.transform(source, result);
            logger.debug("Updated XML: \n" + stringOut.toString());
        }
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }

    return stringOut.toString();
}

From source file:Main.java

public static String documentToString(Document d) {
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = null;
    try {//from ww  w  . j  a  v a2 s  .  c o  m
        transformer = tf.newTransformer();
    } catch (TransformerConfigurationException e) {
        e.printStackTrace();
        return null;
    }
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    StringWriter writer = new StringWriter();
    try {
        transformer.transform(new DOMSource(d), new StreamResult(writer));
    } catch (TransformerException e) {
        e.printStackTrace();
        return null;
    }
    return writer.getBuffer().toString().replaceAll("\n|\r", "");
}

From source file:Main.java

public static String transformXmlToString(Document doc, String encoding)
        throws ParserConfigurationException, TransformerException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = dbf.newDocumentBuilder();

    Document document = builder.newDocument();

    Element e = doc.getDocumentElement();
    Node n = document.importNode(e, true);
    document.appendChild(n);//from  ww w .  j  a  va 2  s .  c om

    // write the content into xml file
    TransformerFactory transformerFactory = TransformerFactory.newInstance();

    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

    DOMSource source = new DOMSource(document);

    StringWriter sw = new StringWriter();

    StreamResult result = new StreamResult(sw);

    transformer.transform(source, result);

    return sw.toString();
}

From source file:com.thinkbiganalytics.feedmgr.nifi.NifiTemplateParser.java

public static String documentToString(Document doc) throws Exception {

    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    StringWriter writer = new StringWriter();
    transformer.transform(new DOMSource(doc), new StreamResult(writer));
    String output = writer.getBuffer().toString();
    return output;
}