Example usage for javax.xml.transform OutputKeys OMIT_XML_DECLARATION

List of usage examples for javax.xml.transform OutputKeys OMIT_XML_DECLARATION

Introduction

In this page you can find the example usage for javax.xml.transform OutputKeys OMIT_XML_DECLARATION.

Prototype

String OMIT_XML_DECLARATION

To view the source code for javax.xml.transform OutputKeys OMIT_XML_DECLARATION.

Click Source Link

Document

omit-xml-declaration = "yes" | "no".

Usage

From source file:Main.java

public static String convertResultSetToXML(ResultSet rs)
        throws SQLException, ParserConfigurationException, TransformerException {
    ResultSetMetaData rsmd = rs.getMetaData();
    int colCount = rsmd.getColumnCount();

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.newDocument();
    Element results = doc.createElement("Results");
    doc.appendChild(results);/* ww w .  j  a  va  2  s.  co m*/

    while (rs.next()) {
        Element row = doc.createElement("Row");
        results.appendChild(row);
        for (int i = 1; i <= colCount; i++) {
            String columnName = rsmd.getColumnName(i);
            Object value = rs.getObject(i);
            if (value != null) {
                Element node = doc.createElement(columnName.replaceAll("\\(", "_").replaceAll("\\)", "_"));
                node.appendChild(doc.createTextNode(value.toString()));
                row.appendChild(node);
            }
        }
    }

    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    StringWriter writer = new StringWriter();
    transformer.transform(new DOMSource(doc), new StreamResult(writer));
    String output = writer.getBuffer().toString().replaceAll("\n|\r", "");

    return output;
}

From source file:Main.java

/**
 * Convert the document to an array of bytes.
 *
 * @param doc The XML document./*from  ww w  .  j a  va 2s. c o  m*/
 * @param encoding The encoding of the output data.
 *
 * @return The XML document as an array of bytes.
 *
 * @throws TransformerException If there is an error transforming to text.
 */
public static byte[] asByteArray(Document doc, String encoding) throws TransformerException {
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

    StringWriter writer = new StringWriter();
    Result result = new StreamResult(writer);
    DOMSource source = new DOMSource(doc);
    transformer.transform(source, result);
    try {
        return writer.getBuffer().toString().getBytes(encoding);
    } catch (UnsupportedEncodingException e) {
        throw new TransformerException("Unsupported Encoding", e);
    }
}

From source file:Main.java

public static void writeTo(Document document, File output) {
    try {//from ww w .j a  va  2  s .  c  o m
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(document);

        FileOutputStream outputstream = new FileOutputStream(output);
        StreamResult result = new StreamResult(outputstream);

        // Manually add xml declaration, to force a newline after it.
        String xmlDeclaration = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
        outputstream.write(xmlDeclaration.getBytes());

        // Remove whitespaces outside tags.
        // Essential to make sure the nodes are properly indented.
        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);
        }

        // Pretty-print options.
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        transformer.transform(source, result);

        outputstream.close();
    } catch (TransformerException | IOException | XPathExpressionException e) {
        System.out.println("Failed to write document file" + output.getPath() + ": " + e.toString());
    }
}

From source file:Main.java

public static String tryFormattingString(String s) {
    try {//from  w  w  w.  j  ava  2s  . com
        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

/**
 * Print the specified XML DOM node to the specified output stream
 * /*from  w  w w .  j a va2s. c om*/
 * @param n
 *            the node to print
 * @param os
 *            the output stream to print to
 * @throws Exception
 */
public static void printNode(Node n, OutputStream os) throws Exception {
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer();
    t.setOutputProperty(OutputKeys.INDENT, "yes");
    t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    t.transform(new DOMSource(n), new StreamResult(os));
}

From source file:Main.java

public static String xmlDocToString(Document document) throws TransformerException {
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    StringWriter writer = new StringWriter();
    transformer.transform(new DOMSource(document), new StreamResult(writer));
    return writer.getBuffer().toString();
}

From source file:Main.java

/**
 * Method to convert document to string.
 * /*w w  w. jav  a  2s  . c om*/
 * @param doc
 * @return document content as string
 */
public static String doc2String(Document doc) {
    try {
        StringWriter sw = new StringWriter();
        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.transform(new DOMSource(doc), new StreamResult(sw));
        return sw.toString();
    } catch (Exception ex) {
        throw new RuntimeException("Error converting to String", ex);
    }
}

From source file:Main.java

public static String toPrettyString(String xml) {
    int indent = 4;
    try {/*  w  w  w . ja  v a 2 s .  c  o  m*/
        // 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);
        }

        // Setup pretty print options
        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, "no");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");

        // Return pretty print xml string
        StringWriter stringWriter = new StringWriter();
        transformer.transform(new DOMSource(document), new StreamResult(stringWriter));
        return stringWriter.toString();
    } catch (Exception e) {
        System.out.println(xml);
        throw new RuntimeException(
                "Problems prettyfing xml content [" + Splitter.fixedLength(100).split(xml) + "]", e);
    }
}

From source file:Main.java

/**
 * Save the XML document to an output stream.
 *
 * @param doc The XML document to save./*from w  ww .j  a  v  a  2 s  . c o m*/
 * @param outStream The stream to save the document to.
 * @param encoding The encoding to save the file as.
 *
 * @throws TransformerException If there is an error while saving the XML.
 */
public static void save(Node doc, OutputStream outStream, String encoding) throws TransformerException {
    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

        // initialize StreamResult with File object to save to file
        Result result = new StreamResult(outStream);
        DOMSource source = new DOMSource(doc);
        transformer.transform(source, result);
    } finally {

    }
}

From source file:Main.java

/**
 * Save the XML document to a file.//from w  ww.j  av  a  2 s  .c  o  m
 * 
 * @param doc
 *            The XML document to save.
 * @param file
 *            The file to save the document to.
 * @param encoding
 *            The encoding to save the file as.
 * 
 * @throws TransformerException
 *             If there is an error while saving the XML.
 */
public static void save(Document doc, String file, String encoding) throws TransformerException {
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    // initialize StreamResult with File object to save to file

    Result result = new StreamResult(new File(file));
    DOMSource source = new DOMSource(doc);
    transformer.transform(source, result);
}