Java – How to format a date or double value when using a simple xml persistent object

How to format a date or double value when using a simple xml persistent object… here is a solution to the problem.

How to format a date or double value when using a simple xml persistent object

I’m using a simple XML framework from http://simple.sourceforge.net/. How do I format a date or double value? I see a function called transform, but how do I apply all its double and date fields in my class?

Solution

I can think of two ways to do this.

First of all:

You can implement your own > You can pass it on Persister When you create it. Your matcher simply returns a Transform for the type you’re interested in. By default, your custom matcher will try any type of those that don’t match. You may want to look at the source code to see how DateTransform and FloatTransform are implemented. They are short, so completely doable. This solution is only useful if you want to convert all types in a specific way.

The second :

Create a String element to hold the serialized data.

@Element(name = "myelement")
private String strMyElement;

private MyElementType myElement;

Then use the @Persist and @Validate annotations to hook into the serialization process.

@Persist
private void persist() {
  strMyElement = myElement.toString();
}

@Validate
private void validate() {
  myElement = myElement.fromString(strMyElement);
}

This way is more like a hack, but it’s useful when you only need to override the default serialization in specific cases. If you have to do this for every instance of a particular type, it can get clunky. In that case, I would use the first method.

Related Problems and Solutions