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

/**
 * Pretty format a given XML document//  w w  w . j av a2 s . c  o m
 *
 * @param strInput
 *            Valid XML document (No validity check yet!)
 * @param nIndent
 *            Indent
 * @return Formatted XML document
 * @throws Exception
 *             in error case
 */
public static String prettyFormat(String strInput, int nIndent) throws Exception {
    try {
        Source xmlInput = new StreamSource(new StringReader(strInput));
        StringWriter stringWriter = new StringWriter();
        StreamResult xmlOutput = new StreamResult(stringWriter);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", nIndent);
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(nIndent));
        transformer.transform(xmlInput, xmlOutput);
        return xmlOutput.getWriter().toString();
    } catch (Exception e) {
        //            Logger.XMLEval.logState("Pretty formatting: " + e.getMessage(), LogLevel.Error);
        throw e;
    }
}

From source file:Main.java

public static String XMLDocumentToString(Document _doc) {
    TransformerFactory transfac = TransformerFactory.newInstance();
    Transformer trans;//from   www  .j a  v a2  s  .c o m
    String xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
    try {
        trans = transfac.newTransformer();

        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        trans.setOutputProperty(OutputKeys.INDENT, "yes");
        StringWriter sw = new StringWriter();
        StreamResult result = new StreamResult(sw);
        DOMSource source = new DOMSource(_doc);
        trans.transform(source, result);
        xmlString += sw.toString();
    } catch (TransformerConfigurationException e) {
        System.out.println("C:" + e.getClass() + "\nM:" + e.getMessage());
        return null;
    } catch (TransformerException e) {
        System.out.println("C:" + e.getClass() + "\nM:" + e.getMessage());
        return null;
    }
    return xmlString;
}

From source file:Main.java

/**
 * Converts an XML String to a Document.
 *
 * @param string//ww  w .  ja v a  2s .  c  o m
 * @return
 * @throws TransformerException
 * @throws ParserConfigurationException
 */
public static Document toDocument(String string) throws TransformerException, ParserConfigurationException {

    // if there is a byte order mark, strip it off.
    // otherwise, we get a org.xml.sax.SAXParseException: Content is not allowed in prolog
    if (string.startsWith("\uFEFF")) {
        string = string.substring(1);
    }

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

    // StringReader source
    Source source = new StreamSource(new StringReader(string));

    // Document result
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document document = builder.newDocument();
    Result result = new DOMResult(document);

    transformer.transform(source, result);
    return document;
}

From source file:Main.java

/**
 * Converts a dom to a String//from   www .j a  v a2  s.  co m
 *
 * @param dom dom to convert
 * @param outputProperties the properties for the String representation of
 * the XML
 * @return the dom as a String
 */
public static String writeDomToString(Document dom, Properties outputProperties) {
    try {
        StringWriter ret = new StringWriter();
        TransformerFactory transFact = TransformerFactory.newInstance();
        // transFact.setAttribute("indent-number", 2);
        Transformer transformer = transFact.newTransformer();
        if (outputProperties != null) {
            transformer.setOutputProperties(outputProperties);
        }
        DOMSource source = new DOMSource(dom);
        StreamResult result = new StreamResult(ret);
        transformer.transform(source, result);
        return ret.toString();
    } catch (Exception e) {
        throw new RuntimeException("Could not write dom to string!", e);
    }
}

From source file:Main.java

public static String prettyXML(String xml, int indent) {
    try {//w  w  w.  jav a  2 s . com
        // Turn xml string into a document
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8"))));

        // Remove whitespaces outside tags
        XPath xPath = XPathFactory.newInstance().newXPath();
        NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']", document,
                XPathConstants.NODESET);

        for (int i = 0; i < nodeList.getLength(); ++i) {
            Node node = nodeList.item(i);
            node.getParentNode().removeChild(node);
        }
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", indent);
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        StringWriter stringWriter = new StringWriter();
        transformer.transform(new DOMSource(document), new StreamResult(stringWriter));
        return stringWriter.toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:Main.java

public static void prettyFormatXml(final InputStream xml, final OutputStream os, final int indent) {
    try {/* www.j  a va 2s . co  m*/
        final Source xmlInput = new StreamSource(xml);
        final StreamResult xmlOutput = new StreamResult(os);
        final TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", indent);
        final Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(xmlInput, xmlOutput);
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:Main.java

/**
 * Prints a Node tree recursively.//  ww  w . j a va  2 s  .c om
 * @param node A DOM tree Node
 * @param encoding character encoding
 * @return An xml String representation of the DOM tree.
 */
public static String print(Node node, String encoding) {
    if (node == null) {
        return null;
    }

    try {
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer();
        transformer.setOutputProperty("omit-xml-declaration", "yes");
        transformer.setOutputProperty("encoding", encoding);
        DOMSource source = new DOMSource(node);
        ByteArrayOutputStream os = new ByteArrayOutputStream(2000);
        StreamResult result = new StreamResult(os);
        transformer.transform(source, result);
        return os.toString(encoding);
    } catch (Exception e) {
        return null;
    }
}

From source file:com.iflytek.spider.util.DomUtil.java

/**
 * save dom into ouputstream/*from w ww  .ja  v a2  s. c om*/
 * 
 * @param os
 * @param e
 */
public static void saveDom(OutputStream os, Element e) {

    DOMSource source = new DOMSource(e);
    TransformerFactory transFactory = TransformerFactory.newInstance();
    Transformer transformer;
    try {
        transformer = transFactory.newTransformer();
        transformer.setOutputProperty("indent", "yes");
        StreamResult result = new StreamResult(os);
        transformer.transform(source, result);
        os.flush();
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace(LogUtil.getWarnStream(LOG));
    } catch (IOException e1) {
        e1.printStackTrace(LogUtil.getWarnStream(LOG));
    } catch (TransformerConfigurationException e2) {
        e2.printStackTrace(LogUtil.getWarnStream(LOG));
    } catch (TransformerException ex) {
        ex.printStackTrace(LogUtil.getWarnStream(LOG));
    }
}

From source file:Main.java

public static Transformer transformer() throws TransformerConfigurationException {
    TransformerFactory tf = TRANSFORMER_FACTORY.get();
    if (tf == null) {
        tf = TransformerFactory.newInstance();
        TRANSFORMER_FACTORY.set(tf);/* www. j  av  a  2s .c o m*/
    }
    return tf.newTransformer();
}

From source file:Main.java

public static String xml(TransformerFactory transformerFactory, Node node) {
    Writer writer = new StringWriter();
    DOMSource source = new DOMSource(node);
    StreamResult result = new StreamResult(writer);
    try {/*from w  w w . j  av  a2s  .  com*/
        transformerFactory.newTransformer().transform(source, result);
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    }
    return writer.toString().replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "");
}