Tuesday May 13, 2008

XML and Java CAPS

I came across a problem the other day that had I thought I'd share. The problem was that I needed a generic XML transformer and identifier. Normally I would build an otd based on the XML schema or DTD, but in this case, a generic option was required.

To get around the problem, I ended up using the DOM parser within java. Java CAPS as its name suggests has Java underneath it all, so everything available to Java is available in Java CAPS.

Below is some sample code (Outside of Java CAPS) that will take in an XML message, identify the first node and return it as a string. The code can be easily modified to be implemented within Java CAPS.

package sun.XMLProcessing;

/**
*
* @author hpaffrath
*/
import java.io.FileInputStream;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.*;

public class XMLTest2 {

public XMLTest2() {

}

public static void main(String args[]) throws Throwable {
System.out.println("Inside XML Test");
String xmlfile = readFile("c:/DATA/input.xml");
//System.out.println("[" + xmlfile + "]");
System.out.println("XML Message Type = [" + messageType(xmlfile) + "]");


}

public static String readFile(String filename) throws Exception {
try {
FileInputStream fis = new FileInputStream(filename);
byte[] b = new byte[fis.available()];
fis.read(b);
return (new String(b));
} catch (Exception e) {
throw new Exception("File could not be read");

}
}

public static String messageType(String xmlMessage) throws Exception {
ByteArrayInputStream bais = new ByteArrayInputStream(xmlMessage.getBytes());
// Create a Dom Parser
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse((InputStream) bais);

Node n = doc.getFirstChild();
return (n.getNodeName());
}


}



With the implementation, I could have happily used other parsers such as xerces or other XML technologies such as XML Beans or JDOM. You don't get the pretty graphics (Well, you do with XML Beans as the class is rendered in the GUI) .

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed