Hey guys. I'm trying to write a small application to convert xml to Java objects. I did a bit of googling on XML processing using Java, specifically using the DOM, but most of the things I've found looks like way too much effort just to process a simple string. (Creating a DocumentBuilderFactory, DocumentBuilder and Document object just to process one line of xml seems like a waste.) The classes I'll be converting will only include primitive types, strings and dates. I wrote my own little class to process XML, and I'd just like to know if there is a better way of doing it. (Perhaps something in javax.xml that I've missed?) My code does not allow dates yet, but that shouldn't be too much of an effort to add.
import java.lang.reflect.*;
import java.io.*;
import java.util.*;
/**
*
* @author codingMonkey
*/
public class XMLTest {
/** Creates a new instance of XMLTest */
public XMLTest() {
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
XMLTest test = new XMLTest();
Object testObject = new XMLTestClass("Test", 1);
String xml = test.convertObjectToXML(testObject);
System.out.println(xml);
testObject = test.convertXmlToObject(xml);
System.out.println("Object: " + testObject);
}
/* Converts a simple object to XML */
public String convertObjectToXML(Object theObject) {
//XML String
StringBuilder xml = null;
try {
//Get the class
Class theClass = theObject.getClass();
//Create the opening XML tag and the first attribute
xml = new StringBuilder("<object class=\"" + theClass.getName() + "\" ");
//Get fields declared in the class
Field[] fields = theClass.getDeclaredFields();
//Loop through all fields and add them to the XML String
for (Field field : fields) {
//Make the field accesible
field.setAccessible(true);
//Append the field name and value to the XML String
xml.append(field.getName() + "=\"" + field.get(theObject) + "\" ");
}
//End the XML tag
xml.append("/>");
//Return the XML String
return xml.toString();
} catch (Exception ex) {
//Print the exception and return null
System.out.println("Exception occured while trying to convert object to xml: " + ex.getMessage());
return null;
}
}
/* Converts an XML String to an object */
public Object convertXmlToObject(String xml) {
try {
//The object to return
Object ret = null;
//Get String between < and />
String nodeData = xml.substring(1, xml.indexOf("/>"));
//Split the String into a String array
String[] data = nodeData.split(" ");
//Check that this is an object node
if (data[0].equals("object")) {
//Get the object's class
Class objectClass = Class.forName(data[1].substring(data[1].indexOf("=") + 2, data[1].lastIndexOf("\"")));
//Create an instance of the class
ret = objectClass.newInstance();
//The current field of the class
Field field = null;
//The value of the current field
String value = null;
//Get attributes
for (int i = 2; i < data.length; i++) {
//Get field from class
field = objectClass.getDeclaredField(data.substring(0, data[i].indexOf("=")));
//Make the field acessible
field.setAccessible(true);
//Get the value of the field
value = data[i].substring(data[i].indexOf("=") + 2, data[i].lastIndexOf("\""));
//Checks the type of field
if (value.matches("[0-9]+")) {
//Number
field.set(ret, Integer.parseInt(value.toString()));
} else {
//String
field.set(ret, value);
}
}
return ret;
} else {
//Throw an exception
throw new Exception("Only object nodes can be converted to objects");
}
} catch (Exception ex) {
//Print the exception and return null
System.out.println("Exception occured while trying to convert xml to object (A possible cause may be that the XML is not well formed): " + ex.getMessage());
return null;
}
}
}
class XMLTestClass {
private String stringVar;
private int intVar;
public XMLTestClass() {
}
public XMLTestClass(String stringVar, int intVar) {
this.stringVar = stringVar;
this.intVar = intVar;
}
@Override
public String toString() {
return "stringVar - " + stringVar + " intVar - " + intVar;
}
}Please excuse all the unnecessary comments, I'm doing a part-time Java course, and this code will eventually form part of a project. (The college loves comments so much, we get penalised for not commenting just about every single line of code.)