Example usage for javax.xml.transform OutputKeys METHOD

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

Introduction

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

Prototype

String METHOD

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

Click Source Link

Document

method = "xml" | "html" | "text" | expanded name.

Usage

From source file:Main.java

/**
 * Saves a WC3 DOM by writing it to an XML document.
 *
 * @param doc The WC3 DOM document object.
 * @param docPath The full path to the XML document.
 * @param encoding Encoding scheme to use for the XML document, e.g.,
 * "UTF-8."//  www .  j a  v  a  2s .  c  om
 * @throws TransformerConfigurationException
 * @throws FileNotFoundException
 * @throws UnsupportedEncodingException
 * @throws TransformerException
 * @throws IOException
 */
public static void saveDocument(final Document doc, String encoding, String docPath)
        throws TransformerConfigurationException, FileNotFoundException, UnsupportedEncodingException,
        TransformerException, IOException {
    TransformerFactory xf = TransformerFactory.newInstance();
    xf.setAttribute("indent-number", 1); //NON-NLS
    Transformer xformer = xf.newTransformer();
    xformer.setOutputProperty(OutputKeys.METHOD, "xml"); //NON-NLS
    xformer.setOutputProperty(OutputKeys.INDENT, "yes"); //NON-NLS
    xformer.setOutputProperty(OutputKeys.ENCODING, encoding);
    xformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); //NON-NLS
    xformer.setOutputProperty(OutputKeys.VERSION, "1.0");
    File file = new File(docPath);
    try (FileOutputStream stream = new FileOutputStream(file)) {
        Result out = new StreamResult(new OutputStreamWriter(stream, encoding));
        xformer.transform(new DOMSource(doc), out);
        stream.flush();
    }
}

From source file:Main.java

public static String toPrettyString(String xml) {
    int indent = 4;
    try {//ww 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);
        }

        // 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

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);/* ww  w .j  a v a2 s  .  c  o  m*/

    // 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:Main.java

/**
 * Write an XML document to the outputstream provided. This will use the provided Transformer.
 * /* ww w . j  a  va  2  s .c  o  m*/
 * @param transformer The transformer (can be obtained from XmlUtils.createIndentingTransformer())
 * @param outputEntry The output stream to write to.
 * @param document The document to write
 */
public static final void writeXml(Transformer transformer, OutputStream outputEntry, Document document) {
    //      Assert.notNull(transformer, "Transformer required");
    //      Assert.notNull(outputEntry, "Output entry required");
    //      Assert.notNull(document, "Document required");
    //      
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    try {
        transformer.transform(new DOMSource(document), createUnixStreamResultForEntry(outputEntry));
    } catch (Exception ex) {
        throw new IllegalStateException(ex);
    }
}

From source file:Main.java

public static String map2Xml(Map<String, String> content, String root_elem_id, String item_elem_id)
        throws Exception {
    DocumentBuilder b = documentBuilder();
    Document doc = b.newDocument();
    String str = null;//  w w  w.  j  ava 2  s.c  om
    SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    Element root = doc.createElement(root_elem_id);
    doc.appendChild(root);

    // Now, add all the children
    for (Entry<String, String> e : content.entrySet()) {
        Element item = doc.createElement(item_elem_id);
        item.setAttribute("id", e.getKey());
        CDATASection data = doc.createCDATASection(e.getValue());
        item.appendChild(data);
        root.appendChild(item);
    }

    try {
        DOMSource ds = new DOMSource(doc);
        StreamResult sr = new StreamResult(out);
        TransformerHandler th = tf.newTransformerHandler();
        th.getTransformer().setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

        Properties format = new Properties();
        format.put(OutputKeys.METHOD, "xml");
        //         format.put("{http://xml. customer .org/xslt}indent-amount", "4");
        //         format.put("indent-amount", "4");
        //         format.put(OutputKeys.DOCTYPE_SYSTEM, "myfile.dtd");
        format.put(OutputKeys.ENCODING, "UTF-8");
        format.put(OutputKeys.INDENT, "yes");

        th.getTransformer().setOutputProperties(format);
        th.setResult(sr);
        th.getTransformer().transform(ds, sr);

        str = out.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return str;
}

From source file:Main.java

public void print(OutputStream out) throws IOException, TransformerException {
    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", "2");

    transformer.transform(new DOMSource(this.doc), new StreamResult(new OutputStreamWriter(out, "UTF-8")));
}

From source file:Main.java

/**
 * Transform document to string representation.
 *
 * @param document/*  w w w  .j a  v  a 2  s  . co m*/
 *            XHTML document
 * @return string representation of document
 * @throws TransformerException
 *             if it is not possible to create a Transformer instance or to transform document
 */
public static String toString(final Document document) throws TransformerException {
    final StringWriter stringWriter = new StringWriter();
    final StreamResult streamResult = new StreamResult(stringWriter);
    final Transformer transformer = TRANSFORMER_FACTORY.get().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, TRANSFORMER_YES);
    // set indent for XML
    transformer.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", "2");
    // not all JavaSE have the same implementation
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    // transformer.setOutputProperty(OutputKeys.METHOD, "html");
    // html method transforms <br/> into <br>, which cannot be re-parsed
    // transformer.setOutputProperty(OutputKeys.METHOD, "xhtml");
    // xhtml method does not work for my xalan transformer
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, TRANSFORMER_YES);
    transformer.transform(new DOMSource(document.getDocumentElement()), streamResult);
    return stringWriter.toString();
}

From source file:IOUtils.java

public static ContentHandler getSerializer(File file) throws IOException, TransformerException {
    final FileWriter writer = new FileWriter(file);

    final TransformerHandler transformerHandler = FACTORY.newTransformerHandler();
    final Transformer transformer = transformerHandler.getTransformer();

    final Properties format = new Properties();
    format.put(OutputKeys.METHOD, "xml");
    format.put(OutputKeys.OMIT_XML_DECLARATION, "no");
    format.put(OutputKeys.ENCODING, "UTF-8");
    format.put(OutputKeys.INDENT, "yes");
    transformer.setOutputProperties(format);

    transformerHandler.setResult(new StreamResult(writer));

    try {/*  w w w.ja  v a2s . c o m*/
        if (needsNamespacesAsAttributes(format)) {
            return new NamespaceAsAttributes(transformerHandler);
        }
    } catch (SAXException se) {
        throw new TransformerException("Unable to detect of namespace support for sax works properly.", se);
    }
    return transformerHandler;
}

From source file:Main.java

/**
 * @param indentation If greater than zero, then the XML will be indented by the value specified
 *//*from  w ww  .ja  va2  s .  c  o m*/
private static Transformer getXMLidentityTransformer(int indentation) throws Exception {
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer t = factory.newTransformer(); // identity transform
    t.setOutputProperty(OutputKeys.INDENT, (indentation != 0) ? YES : NO);
    t.setOutputProperty(OutputKeys.METHOD, "xml"); //xml, html, text
    t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "" + indentation);
    return t;
}

From source file:com.syrup.storage.xml.XmlFactory.java

/**
 * Convert document to string. Helper method.
 * //from   w  w w. j  a  v a2  s.  c  o  m
 * @param document
 *            the document object.
 * @return String.
  * @throws java.io.IOException when unable to write the xml
  * @throws javax.xml.transform.TransformerException when unable to transform the document
 */
public static String documentToString(Document document) throws IOException, TransformerException {
    String soapRequest = null;

    if (document != null) {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, HTTP.UTF_8);
        StreamResult result = new StreamResult(new StringWriter());
        DOMSource source = new DOMSource(document);
        transformer.transform(source, result);
        return result.getWriter().toString();
    }

    return soapRequest;
}