CHAPTER 9 ■ WRITING AND READING XML
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
public class WriteWithDOM {
public static void main (String args[]) {
// Create an empty Document
Document doc = createDocument();
// Create the XML
createElements(doc);
// Create a String representation of the XML
String xmlContent = createXMLString(doc);
// Write the XML to a file
writeXMLToFile(xmlContent);
}
// Here's where we create the (empty for now) XML document private static Document
createDocument() {
Document doc = null;
try {
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
doc = docBuilder.newDocument();
doc.setXmlStandalone(true);
}
catch(ParserConfigurationException pce) {
System.out.println("Couldn't create a DocumentBuilder");
System.exit(1);
}
return doc;
}