views:

50

answers:

2

I am using simple xml framework from http://simple.sourceforge.net/. How can i format the date or double values? I see a function called transform but how do I apply it all double and date fields in my class?

+1  A: 

Simple uses a TransformCache to map types to Transformer objects. So if filed is of a java.lang.Date' type it will use theorg.simpleframework.xml.transform.DateTransform` to transform the Date object to String.

I guess you have to implement a custom Transformer for Date or the primitive long and (temporarily) replace the default Transformer for that type in the cache.

I didn't find any guide too, the drafted strategy is based on a look on the simple sources.

Andreas_D
Thanks Andreas. I was looking at exactly the same but all the classes are package level and hence i can't extend and replace only the 2 transform methods i require :(... Copying all the classes for my custom matcher doesn't look a good way.
Chandra Mohan
+1  A: 

There's two ways I can think of to do this.

First:

You can implement your own Matcher. You can pass this in to the Persister when you create it. Your Matcher only has to return a Transform for the types you are interested in. Any type your custom Matcher does not match is attempted by the default ones. You'll probably have to take a look at the source code and see how the DateTransform and FloatTransform are implemented. They are quite short so it's perfectly doable. This solution will be useful only if you want to transform all types in a specific way.

Second:

Create a String element that will 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 a bit more of a hack but it's useful when you only need to override the default serialization in specific cases. It would probably get unwieldy if you had to do it for every instance of a specific type. In that case I'd use the first method.

Qberticus
Thanks Qberticus. Good suggestions - will try it and update the post.
Chandra Mohan