Java XML Document to String toXmlString(Document doc)

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

Description

to Xml String

License

Apache License

Declaration

public static String toXmlString(Document doc)
        throws TransformerFactoryConfigurationError, TransformerConfigurationException, TransformerException 

Method Source Code

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

import java.io.StringWriter;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;

import org.w3c.dom.Node;

public class Main {

    public static String toXmlString(Document doc)
            throws TransformerFactoryConfigurationError, TransformerConfigurationException, TransformerException {
        String xmlString = null;//w  w  w.j av a  2  s.  c  o m
        TransformerFactory transfac = TransformerFactory.newInstance();
        Transformer trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        trans.setOutputProperty(OutputKeys.INDENT, "yes");
        StringWriter sw = new StringWriter();
        StreamResult result = new StreamResult(sw);
        DOMSource source = new DOMSource(doc);
        trans.transform(source, result);
        xmlString = sw.toString();
        return xmlString;
    }

    public static String toXmlString(Node node)
            throws TransformerFactoryConfigurationError, TransformerConfigurationException, TransformerException {
        String xmlString = null;
        TransformerFactory transfac = TransformerFactory.newInstance();
        Transformer trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        trans.setOutputProperty(OutputKeys.INDENT, "yes");
        StringWriter sw = new StringWriter();
        StreamResult result = new StreamResult(sw);
        DOMSource source = new DOMSource(node);
        trans.transform(source, result);
        xmlString = sw.toString();
        return xmlString;
    }
}

Related

  1. toStructureString(Document document)
  2. toXML(Document document)
  3. toXML(Document dom)
  4. toXml(Document domDoc)
  5. toXmlString(Document doc)
  6. toXMLString(Document doc, boolean includeXMLDecl, boolean indent)
  7. toXmlString(Document document)
  8. write(Document doc)
  9. write(Document doc, Result result)