Output Document to String
In this chapter you will learn:
Convert Document to String
The following code wraps StringWriter
to
StreamResult
. In this way we can convert DOM document
to a string.
import java.io.StringWriter;
//from j a v a2s.co m
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
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;
import org.w3c.dom.Element;
public class Main {
private static void toString(Document newDoc) throws Exception{
DOMSource domSource = new DOMSource(newDoc);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
StringWriter sw = new StringWriter();
StreamResult sr = new StreamResult(sw);
transformer.transform(domSource, sr);
System.out.println(sw.toString());
}
public static void main(String[] args) throws Exception {
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder domBuilder = domFactory.newDocumentBuilder();
Document newDoc = domBuilder.newDocument();
Element rootElement = newDoc.createElement("parent");
newDoc.appendChild(rootElement);
toString(newDoc);
}
}
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » XML