Making XML Writer Application with Java Console

XML or eXtensible MarkUp Language basically is a mark up language that was created by the World Wide Web Consortium (W3C) to overcome HTML (Hyper Text Markup Language). With XML we can make the customizable tags. Practically, nowadays XML is used to any purpose on the computer data technology. The XML is used from the data changing format on a web service to using an xml as data format to store a data like database.
We are not going to discuss the detail of about history XML, the used of XML, how is the future about XML it self. Obviously, now we already knew how important the XML existence on the computer data technology. And it feels good, if we also could implement this XML existence as a special things in our knowledge. To find out more about XML and it’s behavior on the computer data technology, you can find out your own reference freely.
Now, we will try to make a Java console application that have an ability to write a data on a XML format. For this purpose we will try to map a list onto a XML format. Let’s take a look an example list below:
list
If the list above mapped to a XML format, maybe it will looks like below:

<BOOK_CATALOG>
<LIST>
   <CODE>D0001</CODE>
   <TITLE>Mastering Java</TITLE>
   <WRITER>Ian Klause</WRITER>
   <PUBLISHER>Ian Klause</PUBLISHER>
   <YEAR>Ian Klause</YEAR>
</LIST>
<LIST>
   <CODE>D0002</CODE>
   <TITLE>Mastering Tomcat</TITLE>
   <WRITER>Ian McFarland</WRITER>
   <PUBLISHER>Ian McFarland</PUBLISHER>
   <YEAR>Ian McFarland</YEAR>
</LIST>
<LIST>
   <CODE>D0003</CODE>
   <TITLE>Java GUI and Implementation</TITLE>
   <WRITER>Patrick Boyze</WRITER>
   <PUBLISHER>Patrick Boyze</PUBLISHER>
   <YEAR>Patrick Boyze</YEAR>
</LIST>
<LIST>
   <CODE>D0004</CODE>
   <TITLE>Analyse Jboss Flow</TITLE>
   <WRITER>Adelaine Gim</WRITER>
   <PUBLISHER>Adelaine Gim</PUBLISHER>
   <YEAR>Adelaine Gim</YEAR>
</LIST>
</BOOK_CATALOG>

Now we will make a Java console application to handle the making of the list onto a XML data format just like above.

Ok, let’s make this application, first we create am object which it’s properties are headers of the list, let’s make a Java standard object or POJO (Plain Old Java Object) with getter, setter, constructor, and toString method, the codes of this class object is here.

Hmmm, it’s very simple the object class that we already created, even for the constructor we make all this object properties become parameters of the constructor. And then on the last lines there’s a toString methods that will usable to print out all the value of those object properties.

And then let’s make a small class that we will use to serialize XML Document onto a String Buffer, this String Buffer we can use it to print out to a console. Let’s name this class as DomSerializer, this link provides the codes of this class.

Actually the main function of this DomSerializer class is the lines that exist on serializeNode methods, this method reads all the node of the XML document, and then the result will we put on a String Buffer. And then also on this class there’s a method called serialize, this method will called serializedNode method which return a string. You can explore each methods that exist on this class.

And the next step, we will create an application, which this application will have the scenario below:

1. Put on all the data into an array of object.

2. Create an object of a XML document.

3. Convert the XML Document that we have created onto a string using DomSerializer class.

 

To map the list onto an array of object, let’s take a look of this below codes:

 

public class XMLApplication {
.........
.........
public static void main(String[] args) {
  BookCatalog[] catalog = new BookCatalog[4];
  //entrying the data
  catalog[0] = new BookCatalog("D0001", "Mastering Java", "Ian Klause", "Wrox.com", Double.parseDouble("2005"));
  catalog[1] = new BookCatalog("D0002", "Mastering Tomcat", "Ian McFarland", "Wrox.com", Double.parseDouble("2002"));
  catalog[2] = new BookCatalog("D0003", "Java GUI and Implementation", "Patrick Boyze", "Andalusia.com", Double.parseDouble("2001"));
  catalog[3] = new BookCatalog("D0004", "Analyse Jboss Flow", "Adelaine Gim", "Tarkuti.com", Double.parseDouble("2003"));
 ..........
 ........
 .......
}
......

On those lines we can see that first we have created a new array of object with the index of the array is 4, just like the much of the data on the list. And then for each index we fill the value of the object using the object constructor of the BookCatalog that we’ve already created before.

The next step we will make 3 methods on this application, those methods are :

1. getDocumentBuilder, this is the method which have used a DocumentBuilderFactory class that exist on javax.xml.parsers packages. And then this method will return a Document Builder object that we can use to create a XML document on the others method. Let’s take a look of below codes:

public class XMLApplication {
 .........
 .........
 .........
private DocumentBuilder getDocumentBuilder() {
   DocumentBuilderFactory dbf=null;
   DocumentBuilder db=null;
   if ((db == null) || (dbf == null)) {
       // Step 1: create a DocumentBuilderFactory and configure it
       dbf = DocumentBuilderFactory.newInstance();
       // Optional: set various configuration options
       dbf.setValidating(false);
       // Step 2: create a DocumentBuilder that satisfies the constraints
       // specified by the DocumentBuilderFactory
       try {
           db = dbf.newDocumentBuilder();
       }
       catch (ParserConfigurationException pce) {
           System.err.println(pce);
       }
   }
   return db;
}
.........
.........
.........
}

as we can see on those lines, first in this method DocumentBuilderFactory class called and initialized with null value, and then on the if block, DocumentBuilderFactory class created and it’s configured, and then on the try catch block, DocumentBuilder object created and this object will be returned.

2. createXMLTemp, this method have a return value is XML Document, and with it’s parameter which is BookCatalog as an array of objeck. Here’s the codes of this methods:

public class XMLApplication {
  .........
  .........
  .........
private Document createXMLTemp(BookCatalog[] catalog) {
    Document doc = getDocumentBuilder().newDocument();
    Element top = doc.createElement("BOOK_CATALOG");
    doc.appendChild(top);
    Element root = doc.getDocumentElement();
    Element list = null;

    for (int i = 0; i < catalog.length; i++) {
        list = doc.createElement("LIST");

        Element elCode = doc.createElement("CODE");
        Text txtElCode = doc.createTextNode(catalog[i].getBookCode());
        elCode.appendChild(txtElCode);
        list.appendChild(elCode);

        Element elTitle = doc.createElement("TITLE");
        Text txtElTitle = doc.createTextNode(catalog[i].getBookTitle());
        elTitle.appendChild(txtElTitle);
        list.appendChild(elTitle);

        Element elWriter = doc.createElement("WRITER");
        Text txtElWriter = doc.createTextNode(catalog[i].getBookWriter());
        elWriter.appendChild(txtElWriter);
        list.appendChild(elWriter);

        Element elPublisher = doc.createElement("PUBLISHER");
        Text txtElPublisher = doc.createTextNode(catalog[i].getBookWriter());
        elPublisher.appendChild(txtElPublisher);
        list.appendChild(elPublisher);

        Element elYear = doc.createElement("YEAR");
        Text txtElYear = doc.createTextNode(catalog[i].getBookWriter());
        elYear.appendChild(txtElYear);
        list.appendChild(elYear);
        root.appendChild(list);
    }

    return doc;
}

.........

we could see on those lines, the getDocumentBuilder method called to create a new XML document object, and then an element added on the object, this element is the top element of the object and has been named as top, and then there’s a loop do, this loop will rotate the process as much as the BookCatalog object index length, which used as a parameter of this method, on this loop there’s an adding process of few element refers to a header of the list wich is CODE, TITLE, WRITER, PUBLISHER dan YEAR

3. serializeDOM, this is the 3rd method that we’ve made, this method is usable to convert XML document onto a string that we will print out this string into a console. Here’s the codes of our last method.

public class XMLApplication {
   .........
   .........
   .........
 private String serializeDOM(Document doc) throws IOException {
     DomSerializer serializer = new DomSerializer();
     return serializer.serialize(doc);
 }

.........
.........
.........
}

After we finished creating those methods, now let’s continue to the next scenarios that we have arranged, which is Create an object of a XML document and Convert the XML Document that we have created onto a string using DomSerializer class. Please take a look on below codes to finish up the both scenarios:

public class XMLApplication {
    .........
    .........
 public static void main(String[] args) {
     ............
     ............
     XMLApplication app = new XMLApplication();

      //create document Object
      Document doc = app.createXMLTemp(catalog);
      //Serialize document to String
      String output = "";
      try {
          output = app.serializeDOM(doc);
      } catch (IOException e) {
          e.printStackTrace();
      }
      System.out.print(output);
    ......
    ......
    ......
}
 ......
 ......
 ......
}

That is the last two scenarios that we directly implement on above codes, which on the codes we can see that we create an object of document here, and then we convert the document into a string, and the finally we print out the string result onto a console. Okay, this is the link which provides the source of this application file, this file has been optimized in order to make it good on the view and perhaps it’s easy to understand, (Main Application Source Code Link).

That’s it, our experiments this time, this XML Writer Application that we can use to print out a list onto XML format view on the console. Practically, I use this methods to create a servlet that will produce a XML data format. I have used it in a web application, that this web application is responsible for a web service that my company had. The list of data taken from a database and then the XML format view will be handled by a servlet and the servlet will be requested through http port.

Indeed, it’s my plan to write this XML Writer application that print out into a console, because I think if we discuss it on web application environment and the database included, this article will be so big and it’s hard to understand, because there will be some layers included, such as DAO layer, presentation layer, etc. While those layers have a focus that split between this XML Writer application and those layers it’s self.

Please explore this application to be a wider scale of usage more than we have created above. I hope this article can be a reference for this blog reader generally and especially my self, on how to write XML document format and it’s implementation using Java programming language..

 

I hope this will helpful.

Menteng, 9 December 2009

 

josescalia.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s