/** * This parser outputs an XML document to System.out * @author Nauman Chaudhry * @date Apr 6, 08 */ import javax.xml.parsers.*; import javax.xml.transform.*; import javax.xml.transform.dom.*; import javax.xml.transform.stream.*; import org.w3c.dom.*; import java.io.*; public class Ex6CreateDoc { public static void main(String[] args) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = null; try { db = dbf.newDocumentBuilder(); } catch (ParserConfigurationException pce) { pce.printStackTrace(); return; } // Create a Document with root element named "account" Document doc = db.getDOMImplementation().createDocument( null, "customer", null); Element root = doc.getDocumentElement(); // Set couple of attributes on the element with tag name account root.setAttribute("customer_num", "_1"); root.setAttribute("social_sec_num", "112233445"); // Create an account type and set it as a child of account Element accType = doc.createElement("account_type"); root.appendChild(accType); // The content of account type is text Text accTypeText = doc.createTextNode("S"); accType.appendChild(accTypeText); // We now need to print the contents of this XML document to // System.out TransformerFactory tf = TransformerFactory.newInstance(); Transformer trans = tf.newTransformer(); trans.transform(new DOMSource(doc), new StreamResult(System.out)); } }