Monday, July 24, 2006

Java: Using Apache Xerces to Write XML Files

Another thing I have been playing with is XML using Apache Xerces. I plan to use XML files to store configuration information for programs. I also use several programs that use XML as a data file formats, and I need an easy way to parse various info from them. The following example will write out an XML file with a structure like so:


The code is below:
package xmlTest;

import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.apache.xml.serialize.*;

public class XMLTestImpl {

     * @param args
     public static void main(String[] args) {
          DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
          Element el;
          DocumentBuilder db = null;
          Document doc = null;
          Element root = null;
          XMLSerializer xmlSer;
          OutputFormat out;
          //Try to create the document builder
               db = dbf.newDocumentBuilder();
               doc = db.newDocument();
          catch (Exception e)
          //Creat the root class, called TEst
          root = doc.createElement("Test");
          //Create child node to root
          el = doc.createElement("child1");
          //Set some arbitrary attribute
          root.setAttribute("String1", "root_node");
          el.setAttribute("String2", "child_node");
          //Write out to file using the serializer
               out = new OutputFormat(doc);
               xmlSer = new XMLSerializer(
               new FileOutputStream(new File("/tmp/test.xml")), out);
          catch(Exception e)


Anonymous said...

Hey John, just following up from the conference had a look at your site? Have you had a look at jaxb? Pretty cools stuff, given an XSD it will automagically create the classes to marshal/unmarshal between java and XML.


John Ortiz OrdoƱez said...

This mini-tutorial has been useful for me to start creating XML files. Thanks for this help. See you later.

P.S.: Do you know where I can find more examples?