I have been trying to create an XML using the simplexml library (v2.6.2)
http://simple.sourceforge.net/home.php
The XML I want to create has to hold an enum value, which should be case-sensitive. Following is the POJO :
package pojos;
public enum MyEnum {
NEW("new"),
OLD("old");
private final String value;
MyEnum(String v)
{
value = v;
}
public String value() {
return value;
}
public static MyEnum fromValue(String v) {
for (MyEnum c: MyEnum.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
Following is the serializer code :
import java.io.File;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
import pojos.MyEnum;
public class TestEnum {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Serializer serializer = new Persister();
MyEnum example = MyEnum.NEW;
File result = new File("myenum.xml");
serializer.write(example, result);
}
}
The resultant output :
<myEnum>NEW</myEnum>
The desired output :
<myEnum>new</myEnum>
How should I proceed ? I cannot change the variable name in the enum as it happens to be the keyword “new” !
Thanks.
After some investigation of the source code, i have discovered that the library uses interface
Transformto transform values to Strings. The default behavior of enum transformations is defined by classEnumTransform. In order to customize that, you can define you own Transform class. The following version ofTransformimplementation would calltoString()instead of the defaultname()on the enum objects.Transformobjects are returned frommatchmethod by objects ofMatcherinterface. There could be severalMatcherobjects. The library tries them one by one until it finds one that returns a non-nullTransformerobject. You can define your ownMatcherobject and pass it as argument to the constructor ofPersisterclass. This object will get the highest priority.Finally, you wont forget to define a toString method on your enum classes. Then the combination of codes above will do you the work of encoding enum objects using their toString values.