Sunday, January 18, 2009

More On Writing XML In Java

After trying JDOM, I just had to check out the built-in XML features of the Java Development Kit. I used the Java API for XML Processing with the Apache Xerces underneath (included with Sun's JDK 6). Here's the sample I came up with:

import javax.xml.parsers.*;
import org.w3c.dom.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DOMImplementation di = dbf.newDocumentBuilder().getDOMImplementation();
Document doc = di.createDocument("", "rootElement", null);
Element el = doc.createElement("childElement");
Transformer trans = TransformerFactory.newInstance().newTransformer();
DOMSource ds = new DOMSource(doc);
FileOutputStream fostr = new FileOutputStream("xmlout.xml");
StreamResult strResult = new StreamResult(fostr);
trans.transform(ds, strResult);

No comments: