Extracting an XML formatted string out of a DOM object : XML Serialization « XML « Java Tutorial






import java.io.StringWriter;

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 void main(String[] argv) throws Exception {
  }

  static String getXMLString(Document xmlDoc) throws Exception {
    StringWriter writer = null;
    DOMSource source = new DOMSource(xmlDoc.getDocumentElement());
    writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer();
    transformer.transform(source, result);
    StringBuffer strBuf = writer.getBuffer();
    return strBuf.toString();
  }
}








33.21.XML Serialization
33.21.1.Saving a DOM tree to XML file javax.xml.parsers (JAXP)
33.21.2.PropsToXML takes a standard Java properties file, and converts it into an XML file
33.21.3.Writing a DOM Document to an XML File
33.21.4.Writing Only the Text of a DOM Document
33.21.5.Create an XML document with DOM
33.21.6.Strip extra spaces in a XML string
33.21.7.Extracting an XML formatted string out of a DOM object