XML handling using JDOM..

Posted by Shashank Krishna Saturday, August 1, 2009


sharethis:

What is JDOM?

  • A Pure Java API for reading and writing XML Documents

  • A Java-oriented API for reading and writing XML Documents

  • A tree-oriented API for reading and writing XML Documents

  • A parser independent API for reading and writing XML Documents

Here is a simple java code which generates a simple xml file:



< ?xml version="1.0" encoding="UTF-8"? >
Hello JDOM!


The relevant code is


import org.jdom.*;
import org.jdom.output.XMLOutputter;


public class HelloJDOM {

public static void main(String[] args) {

Element root = new Element("GREETING");

root.setText("Hello JDOM!");

Document doc = new Document(root);

// At this point the document only exists in memory.
// We still need to serialize it
XMLOutputter outputter = new XMLOutputter();
try {
outputter.output(doc, System.out);
}
catch (Exception e) {
System.err.println(e);
}

}

}



See,how simple is it....Now if we wanted to do this using the usual DOM....


import java.io.*;
import org.w3c.dom.*;
import org.apache.xerces.dom.*;
import org.apache.xml.serialize.*;


public class HelloDOM {

public static void main(String[] args) {

try {

DOMImplementationImpl impl = (DOMImplementationImpl)
DOMImplementationImpl.getDOMImplementation();

DocumentType type = impl.createDocumentType("GREETING", null, null);

// type is supposed to be able to be null,
// but in practice that didn't work
DocumentImpl hello
= (DocumentImpl) impl.createDocument(null, "GREETING", type);

Element root = hello.createElement("GREETING");

// We can't use a raw string. Instead we have to first create
// a text node.
Text text = hello.createTextNode("Hello DOM!");
root.appendChild(text);

// Now that the document is created we need to *serialize* it
try {
OutputFormat format = new OutputFormat(hello);
XMLSerializer serializer = new XMLSerializer(System.out, format);
serializer.serialize(root);
}
catch (IOException e) {
System.err.println(e);
}
}
catch (DOMException e) {
e.printStackTrace();
}

}

}


Now this is trouble some....

Hope u enjoyed the post....Comment if u like it... :)

Reactions: 
Spread Firefox Affiliate Button | edit post .

1 Comment

  1. dontcare Says,

    VTD-XML is 10x faster and 5x more memory efficient than JDOM
    or DOM4J

    http://vtd-xml.sf.net

     

Post a Comment

Are You Planning on Quitting Facebook? Why?

@Flickr

www.flickr.com

About Me

My Photo
Shashank Krishna
Bangalore, up, India
nothin much to say.........doin B.tech in IIIT allahabad loves bloggingn hacking.... :) and loooves blogging
View my complete profile

ads2

topads