I really like the XStream
library. It does a really good job of outputting fairly simple xml
as a result of a provided Java object. It works great for reproducing
the object back from the xml as well. And, one of our 3rd party libraries
already depended on it anyway.
We chose to use it because we wanted
our xml to be human readable. Using
the alias function makes it much
nicer.
You can extend the library if you
want some portion of an object to
deserialize in a nicer fashion. We
did this in one case so the file
would have a set of degrees,
minutes, and seconds for a latitude
and longitude, instead of two
doubles.
The two minute tutorial sums up the basic usage, but in the
interest of keeping the information in one spot, I'll try to sum it
up here, just a little shorter.
// define your classes
public class Person {
private String firstname;
private PhoneNumber phone;
// ... constructors and methods
}
public class PhoneNumber {
private int code;
private String number;
// ... constructors and methods
}
Then use the library for write out the xml.
// initial the libray
XStream xstream = new XStream();
xstream.alias("person", Person.class); // elementName, Class
xstream.alias("phone", PhoneNumber.class);
// make your objects
Person joe = new Person("Joe");
joe.setPhone(new PhoneNumber(123, "1234-456"));
// convert xml
String xml = xstream.toXML(joe);
You output will look like this:
<person>
<firstname>Joe</firstname>
<phone>
<code>123</code>
<number>1234-456</number>
</phone>
</person>
To go back:
Person newJoe = (Person)xstream.fromXML(xml);
The XMLEncoder is provided for Java bean serialization. The last time I used it,
the file looked fairly nasty. If really don't care what the file looks like, it could
work for you and you get to avoid a 3rd party dependency, which is also nice. I'd expect the possibility of making the serialization prettier would be more a challenge with the XMLEncoder as well.
XStream outputs the full class name if you don't alias the name. If the Person class above had
package example;
the xml would have "example.Person" instead of just "person".