I would like to serialize an object to an XML of this form with XStream.
text
There already is a solutio
It's possible with some hacks. The main idia is to use a modified ToAttributedValueConverter
from 1.4.7.
ToAttributedValueConverter
into your packageUseAttributeForEnumMapper
into your packageReplace ToAttributedValueConverter#fieldIsEqual
as follows:
private boolean fieldIsEqual(FastField field) {
return valueField.getName().equals(field.getName())
&& valueField.getDeclaringClass().getName()
.equals(field.getDeclaringClass().getName());
}
Replace the Constructor in UseAttributeForEnumMapper
as follows:
public UseAttributeForEnumMapper(Mapper wrapped) {
super(wrapped, null);
}
It is not possible to use the @XStreamConverter
annotation, becouse the ToAttributedValueConverter
has a constrcutor that needs some extra information, like the value field. But you can use XStream#registerConverter
alternativly. So your class have to look like:
@XStreamAlias("node")
public class Node {
private String attr;
private String content;
public void setAttr(String attr) { this.attr = attr; }
public String getAttr() { return attr; }
public void setContent(String content) { this.content = content; }
public String getContent() { return content; }
}
And a example that shows how to configure xstream for this converter:
public static void main(String[] args) {
final Node node = new Node();
node.setAttr("value");
node.setContent("text");
final XStream xstream = new XStream();
configureXStream(xstream);
final String xml = xstream.toXML(node);
System.out.println(xml);
final Node node2 = (Node) xstream.fromXML(xml);
System.out.println("attr: " + node2.getAttr());
System.out.println("content: " + node2.getContent());
}
private static void configureXStream(final XStream xstream) {
xstream.autodetectAnnotations(true);
final Mapper mapper = xstream.getMapper();
final ReflectionProvider reflectionProvider = xstream
.getReflectionProvider();
final ConverterLookup lookup = xstream.getConverterLookup();
final Converter converter = new ToAttributedValueConverter(Node.class,
mapper, reflectionProvider, lookup, "content");
xstream.registerConverter(converter);
}
This program prints out:
text
attr: value
content: text