Java XML Document Serialize serializeDocument(Document doc)

Here you can find the source of serializeDocument(Document doc)

Description

serialize a Document in a XML UTF8 String

License

Apache License

Parameter

Parameter Description
doc Dom Document to serialiaze

Exception

Parameter Description
TransformerException an exception

Return

@throws IOException

Declaration

public static String serializeDocument(Document doc) throws IOException, TransformerException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;

public class Main {
    /**/*from  ww  w. j  a v  a2 s.  c o m*/
     * serialize a Document in a XML UTF8 String
     * 
     * @param doc
     *            Dom Document to serialiaze
     * @return @throws IOException
     * @throws TransformerException
     */
    public static String serializeDocument(Document doc) throws IOException, TransformerException {
        ByteArrayOutputStream s = new ByteArrayOutputStream();

        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        DOMSource source = new DOMSource(doc);
        StreamResult outputTarget = new StreamResult(s);
        transformer.transform(source, outputTarget);

        return s.toString("UTF8");
    }
}

Related

  1. serialize(Document document, OutputStream out)
  2. serialize(Document document, String fileName)
  3. serialize(Document document, Writer writer)
  4. serialize(final Document doc, final OutputStream os, final String encoding)
  5. serialize(final Document document, final OutputStream out)
  6. serializeDocument(Document doc, String filePath)
  7. serializeDocument(Document document)
  8. serializeDocument(Document document, OutputStream os)
  9. serializeDocument(Document root)