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

/**
 * convert node object into String object.
 * @param node//from w  w w  .ja va  2  s  . c om
 * @param omitXmlDecl
 * @return
 */
public static String dom2String(Node node, boolean omitXmlDecl) {
    Source source = new DOMSource(node);
    StringWriter stringWriter = new StringWriter();
    Result result = new StreamResult(stringWriter);
    try {
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();
        if (omitXmlDecl)
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.transform(source, result);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return stringWriter.getBuffer().toString();
}

From source file:Main.java

public static ByteArrayOutputStream printDOMDocumentToOutputStream(Document doc) {
    ByteArrayOutputStream os;/*w  w w . ja  v  a 2  s . c  om*/
    os = new ByteArrayOutputStream();

    try {
        // TODO remove, nonsence here XMLSignatureHelper.storeSignatureToXMLFile(doc, "signature.xml");

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer trans = tf.newTransformer();
        //trans.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        //trans.setOutputProperty(OutputKeys.INDENT, "yes");
        //trans.setOutputProperty(OutputKeys.METHOD, "xml");

        trans.transform(new DOMSource(doc), new StreamResult(os));

    } catch (TransformerConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TransformerFactoryConfigurationError e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TransformerException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return os;

}

From source file:Main.java

/**
 * Returns the String-Representation of the given DOM-Node as well-formed DOM-Document.
 *
 * @param node DOM-Node to print/*from  w  w  w  .  j a va2s  .  c o  m*/
 * @param indent if true resulting XML is endented
 * @return <code>String</code> - Node as XML-String
 * @throws Exception on error
 */
public static String domNode2String(Node node, boolean indent) throws Exception {
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, indent ? "yes" : "no");

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

    String xmlString = result.getWriter().toString();

    return xmlString;
}

From source file:Main.java

public static String getXML(NodeList childNodes) {
    try {// w  ww.j av  a 2 s.c  o  m
        StringBuilder builder = new StringBuilder();
        Transformer t = TransformerFactory.newInstance().newTransformer();
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        for (int i = 0; i < childNodes.getLength(); i++) {
            StringWriter sw = new StringWriter();
            t.transform(new DOMSource(childNodes.item(i)), new StreamResult(sw));
            builder.append(sw.toString());
        }
        return builder.toString();
    } catch (Exception ex) {
        return "";
    }
}

From source file:Main.java

/**
 * Save a DOM document//from w ww.j av  a2  s  .co m
 */
public static void saveDocument(Document document, OutputStream out, boolean indent) throws IOException {
    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        if (indent) {
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        }
        transformer.transform(new DOMSource(document), new StreamResult(out));
    } catch (TransformerException e) {
        throw new IOException(e.getMessage());
    }
}

From source file:Main.java

public final static void applyXSLTTransform(final Reader xslt, final Reader input, final Writer output)
        throws TransformerException {
    final Transformer transformer = transformerFactory.newTransformer(new StreamSource(xslt));

    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, OUTPUT_PROPERTY_YES);
    transformer.setOutputProperty(OutputKeys.INDENT, OUTPUT_PROPERTY_NO);

    transformer.transform(new StreamSource(input), new StreamResult(output));
}

From source file:Main.java

public static String prettyFormat(String input, int indent, boolean isOmitXmlDeclaration) {
    try {/* ww  w .jav a  2  s . c o  m*/
        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");
        if (isOmitXmlDeclaration) {
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        }
        transformer.transform(xmlInput, xmlOutput);
        return xmlOutput.getWriter().toString();
    } catch (Exception e) {
        throw new RuntimeException(e); // simple exception handling, please review it
    }
}

From source file:Main.java

public static void hashMapToXML222(String xmlFile, String xpath, HashMap hashmap) {
    try {/*from   ww w.  j a v  a2 s.  co  m*/
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.newDocument();

        Element rootNode = document.createElement(xpath);
        document.appendChild(rootNode);

        Set set = hashmap.entrySet();
        Iterator i = set.iterator();

        while (i.hasNext()) {
            Map.Entry me = (Map.Entry) i.next();
            Element em = document.createElement(me.getKey().toString());
            em.appendChild(document.createTextNode(me.getValue().toString()));
            rootNode.appendChild(em);
            // System.out.println("write " +
            // me.getKey().toString() + "="
            // + me.getValue().toString());
        }

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(document);
        FileOutputStream fo = new FileOutputStream(xmlFile);
        StreamResult result = new StreamResult(fo);
        transformer.transform(source, result);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:Main.java

public static void toWriter(Document doc, Writer writer) {
    if (doc == null || writer == null) {
        return;/* w  ww.j a v a2s. c o  m*/
    }
    try {
        Transformer tran = tf.newTransformer();
        tran.setOutputProperty(OutputKeys.INDENT, "yes");
        tran.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        Source src = new DOMSource(doc);
        Result res = new StreamResult(writer);
        tran.transform(src, res);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static void pokeValue(final File file, final String xpathExpression, final String value)
        throws XPathExpressionException, ParserConfigurationException, SAXException, IOException,
        TransformerException {/*w w w  .j  a  v  a2s.  co m*/
    // TODO: it might be better performance to do a SAX read/write
    final DocumentBuilder db = DBF.newDocumentBuilder();
    final FileInputStream fis = new FileInputStream(file);
    final Document doc;
    try {
        doc = db.parse(fis);
    } finally {
        fis.close();
    }

    pokeValue(doc, xpathExpression, value);

    final Transformer t = TF.newTransformer();
    final DOMSource source = new DOMSource(doc);
    final FileOutputStream fos = new FileOutputStream(file);
    try {
        final StreamResult result = new StreamResult(fos);
        t.transform(source, result);
    } finally {
        fos.close();
    }
}