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:

-Root(String1=Root_Node)
------Child(String2=child_node)

The code is below:
package xmlTest;

import java.io.File;
import java.io.FileOutputStream;
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
          try
          {
               db = dbf.newDocumentBuilder();
               doc = db.newDocument();
          }
          catch (Exception e)
          {
               e.printStackTrace();
               System.exit(1);
          }
          
          //Creat the root class, called TEst
          root = doc.createElement("Test");
          doc.appendChild(root);
          
          //Create child node to root
          el = doc.createElement("child1");
          root.appendChild(el);
          
          //Set some arbitrary attribute
          root.setAttribute("String1", "root_node");
          el.setAttribute("String2", "child_node");
          
          //Write out to file using the serializer
          try
          {
               out = new OutputFormat(doc);
               out.setIndenting(true);
               
               xmlSer = new XMLSerializer(
               new FileOutputStream(new File("/tmp/test.xml")), out);
               xmlSer.serialize(doc);
          }
          catch(Exception e)
          {
               e.printStackTrace();
          }
     }
}

2 comments:

Scott Rosenbaum 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.

Scott

John Ortiz 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?