Generate XML from a arbitrary java object.

I have like 50 Java Objects which I want to spit them as XML.

Is there a generic way to ouput a XML without having to write a special parser for each object and then writing a stream of XML.

Each of my Java object is like a TransferObject or a Value Object with set and get convention with properites as private.

Also my client who  is reveiving this XML is non-java. Infact it is a HTA container (a microsoft product for DHTML) so using the XMLSerializer by SUN is not a good option which I was exploring.

Some code will really help.


Who is Participating?
If the only values you are looking to place into the XML are all supported by get*() methods, you can use the reflection API to generate a simple XML structure.

int index;
Class cl = object.class;
System.out.println("<class type=\"" + cl.getName() + "\">");
Method [] methods = cl.getMethods();
for (index = 0 ; index < methods.length ; ++index)
   String name = methods[index].getName();
   Class [] params = methods[index].getParameterTypes();
   if (name.startsWith("get") && (params == null || params.length == 0))
      System.out.println("<field id=\"" + name.substring(3) + " \"  value=\"" + methods[index].invoke(object, null).toString() + "\" />");

This is a rough layout of the code, but you will want to add exception handling and output to the correct destination file.
>>get*() methods, you can use the reflection API to generate a simple XML structure.

There's no need to reinvent the wheel in that way as that's precisely what XMLEncoder does
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.