Programming and writing about it.

echo $RANDOM

ODF Toolkit for Java

I have decided to discontinue my dedicated blog on ODF Toolkit for Java, basically because I was finding it difficult to manage both.

From now on, all posts on ‘odf4j’ will be available here on this blog.

Some related links:

We also have a weekly meeting every Friday at 07:30 GMT on irc://freenode/#odftoolkit

Advertisement

Store data in a XML file using the DOM API in JAXP

Okay, if you are like me- a Java developer and think that XML is an easy solution to most of your light-weight, persistent data storage and retrieval needs, simply because of its structured nature, I shall briefly describe you how I use Java API for XML processing (JAXP)- DOM API to store and facilitate easy retrieval of data for my application.

Here it goes:

Say, I have some information which I want to store (from my application) as given in file mapping.xml

While coding up the Java class which will write the data into a XML file, the DOM approach is:

  1. Create the DOM representation of the data- this is the in-memory representation
  2. Write it to the XML file using classes from javax.xml.transform package which transforms the DOM representation into the persistent XML file

The code that I would use has two parts to it:

  1. First part deals with the scenario in which the XML file already exists
  2. Second part takes care of the scenario in which I am creating the XML file for the first time- this time the root element of the XML has to be created, which is the difference from the first part

The above logic can be easily implemented using:


String xmlFile = "mapping.xml";
File file = new File(xmlFile);
if (file.exists()) {
//then code for first part
}else
{
//code for second part
}

Here is the Java source code:


private void writeToXML(String arg1, String arg4, String arg7) throws IOException, SAXException, ParserConfigurationException {



String xmlFile = "mapping.xml";
File file = new File(xmlFile);
if (file.exists()) {



DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

// Create the builder and parse the file


Document doc = factory.newDocumentBuilder().parse(xmlFile);

org.w3c.dom.Element mddevice = doc.getDocumentElement();

org.w3c.dom.Element new_mddevice = doc.createElement("mddevice");


new_mddevice.setAttribute("name", arg1);

org.w3c.dom.Element blockdevice = doc.createElement("device");

blockdevice.setAttribute("name", arg4);

new_mddevice.appendChild(blockdevice);

org.w3c.dom.Element mountpoint = doc.createElement("mountpoint");
new_mddevice.appendChild(mountpoint);
mountpoint.setTextContent(arg7);

mddevice.appendChild(new_mddevice);

try {
TransformerFactory tranFactory = TransformerFactory.newInstance();
Transformer aTransformer = tranFactory.newTransformer();

Source src = new DOMSource(doc);
System.out.println("Starting the XML file creation");

Result dest = new StreamResult("mapping.xml");
aTransformer.transform(src, dest);


} catch (Exception e) {
System.out.println("Stream error" + e.getMessage());
}
} else {


try {


//Create instance of DocumentBuilderFactory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//Get the DocumentBuilder
DocumentBuilder docBuilder = factory.newDocumentBuilder();
//Create blank DOM Document
org.w3c.dom.Document doc = docBuilder.newDocument();


//create the root element
org.w3c.dom.Element root = doc.createElement("raidmap");

doc.appendChild(root);

org.w3c.dom.Element mddevice = doc.getDocumentElement();
org.w3c.dom.Element new_mddevice = doc.createElement("mddevice");


new_mddevice.setAttribute("name", arg1);

org.w3c.dom.Element blockdevice = doc.createElement("device");

blockdevice.setAttribute("name", arg4);

new_mddevice.appendChild(blockdevice);

org.w3c.dom.Element mountpoint = doc.createElement("mountpoint");
new_mddevice.appendChild(mountpoint);
mountpoint.setTextContent(arg7);





mddevice.appendChild(new_mddevice);
try {
TransformerFactory tranFactory = TransformerFactory.newInstance();
Transformer aTransformer = tranFactory.newTransformer();

Source src = new DOMSource(doc);
Result dest = new StreamResult("mapping.xml");
aTransformer.transform(src, dest);




} catch (Exception e) {
System.out.println("Stream error" + e.getMessage());
}

} catch (Exception e) {
System.err.println(e.toString());
}
}
}

Note: arg1, arg4, arg7 are the “data” that I will store in the XML file; please
change it to suit your needs

Related:

DOM Tree Scanner in NetBeans 6.1 Beta

Say, you have created (or otherwise) a DTD file (for eg. mapping.dtd).

Right-click on it and you will see a option “Generate DOM Tree Scanner” in the pop-up menu that appears. Click on it:

What you will have is a Java class which is all set to be used to scan through your XML file which conforms to your DTD. Its Magic!

In the Java class that is generated, you will see a method:



public void visitDocument() {
.
.
.
}

This will be your entry-point to the DOM scanner.

Just create another Java class:


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package softwareraidtool;


import java.io.IOException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

/**
*
* @author amit
*/
public class MappingScannerDemo {


public static void main(String args[]) throws IOException, SAXException{
try{

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// Create the builder and parse the file
Document doc = factory.newDocumentBuilder().parse("mapping.xml"); //the file you want to parse and which conforms to the DTD
MappingScanner demo = new MappingScanner(doc);

demo.visitDocument();
}catch(ParserConfigurationException pc){

}
}


}

You will have to modify the DOM scanner class to fit your needs. In its original form, it will just parse the XML file.

Here are the files:

HTH, have fun!