I don't know of a ready-to-use converter that will do it, but it's pretty trivial to write one
import com.thoughtworks.xstream.converters.*;
import com.thoughtworks.xstream.io.*;
public class ValueAttributeConverter implements Converter {
public boolean canConvert(Class cls) {
return (cls == String.class);
}
public void marshal(Object source, HierarchicalStreamWriter w, MarshallingContext ctx) {
w.addAttribute("value", (String)source);
}
public Object unmarshal(HierarchicalStreamReader r, UnmarshallingContext ctx) {
return r.getAttribute("value");
}
}
You can attach the converter to the relevant fields using annotations
import com.thoughtworks.xstream.annotations.*;
@XStreamAlias("person")
public class Person {
private String firstname;
private String lastname;
@XStreamConverter(ValueAttributeConverter.class)
private String phone;
@XStreamConverter(ValueAttributeConverter.class)
private String fax;
// add appropriate constructor(s)
/** For testing purposes - not required by XStream itself */
public String toString() {
return "fn: " + firstname + ", ln: " + lastname +
", p: " + phone + ", f: " + fax;
}
}
To make this work, all you need to do is instruct XStream to read the annotations:
XStream xs = new XStream();
xs.processAnnotations(Person.class);
Person p = (Person)xs.fromXML(
"<person>\n" +
" <firstname>Joe</firstname>\n" +
" <lastname>Walnes</lastname>\n" +
" <phone value='1234-456' />\n" +
" <fax value='9999-999' />\n" +
"</person>");
System.out.println(p);
// prints fn: Joe, ln: Walnes, p: 1234-456, f: 9999-999