Java XML Document Save to File saveToXmlStr(Document doc)

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

Description

serializing a XML DOM Document into XML String

License

Open Source License

Parameter

Parameter Description
doc a parameter

Exception

Parameter Description
TransformerException an exception

Return

the string in XML format

Declaration

public static String saveToXmlStr(Document doc) throws DOMException, TransformerException 

Method Source Code

//package com.java2s;

import java.io.StringWriter;

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.DOMException;

import org.w3c.dom.Document;

public class Main {
    /**//from   w  w  w .  j  a  v a2s .c  o m
     * serializing a XML DOM <code>Document</code> into XML String
     * 
     * @param doc
     * @return the string in XML format
     * @throws TransformerException
     */
    public static String saveToXmlStr(Document doc) throws DOMException, TransformerException {
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();

        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        // create string from xml tree
        StringWriter sw = new StringWriter();
        StreamResult result = new StreamResult(sw);
        DOMSource source = new DOMSource(doc);
        transformer.transform(source, result);
        String xmlString = sw.toString();
        return xmlString;

    }
}

Related

  1. saveTemporaryDocument(Document document, String folderName)
  2. saveToDisk(Document doc, OutputStream out)
  3. saveToFile(Document doc, File f, boolean indent)
  4. saveToFile(String filename, Document document)
  5. saveToXml(Document doc, OutputStream os)
  6. saveXML(Document doc, ByteArrayOutputStream outputStreamXML)
  7. saveXML(Document doc, File outfile, boolean indent)
  8. saveXml(Document doc, String filename)
  9. saveXML(Document document, String filename)