Java XML Document to String toXMLString(Document doc, boolean includeXMLDecl, boolean indent)

Here you can find the source of toXMLString(Document doc, boolean includeXMLDecl, boolean indent)

Description

to XML String

License

Open Source License

Declaration

public static String toXMLString(Document doc, boolean includeXMLDecl, boolean indent) 

Method Source Code


//package com.java2s;

import java.io.StringWriter;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
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 {
    public static String toXMLString(Document doc, boolean includeXMLDecl, boolean indent) {
        String xmlString = null;// ww w. j  a  v a  2  s .  c  om
        try {
            TransformerFactory transfac = TransformerFactory.newInstance();
            Transformer trans = transfac.newTransformer();
            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, includeXMLDecl ? "yes" : "no");
            trans.setOutputProperty(OutputKeys.INDENT, indent ? "yes" : "no");

            //create string from xml tree
            StringWriter sw = new StringWriter();
            StreamResult result = new StreamResult(sw);
            DOMSource source = new DOMSource(doc);
            trans.transform(source, result);
            xmlString = sw.toString();
        } catch (Exception ex) {
            throw new RuntimeException("Error trying to render DOM to XML String");
        }
        return xmlString;
    }
}

Related

  1. toXML(Document document)
  2. toXML(Document dom)
  3. toXml(Document domDoc)
  4. toXmlString(Document doc)
  5. toXmlString(Document doc)
  6. toXmlString(Document document)
  7. write(Document doc)
  8. write(Document doc, Result result)
  9. write(String filename, Document document, boolean addDocType)