user496934 user496934 - 9 months ago 54
Java Question

Convert Java to XML using xstream

I have started using the xstream library to convert from Java code to XML. My model java class is simple and given below:

class Person {
String firstname;
String lastname;
String age;
public Person(String first, String last,String age) {
firstname = first;
lastname = last;
this.age = age;

So using simple xstream API I am getting the output of the
method as below:


However, I want to tweak the output and get the string age as an attribute of the field firstname. In essence, I am expecting the xml output as below:

<firstname age="34">David</firstname>

Any help on how to do this would be highly appreciated.


You can use XStream.useAttributeFor() to declare a property to be serialized as an attribute:

xstream.useAttributeFor(Person.class, "age");