user496934 user496934 - 4 years ago 211
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.

Answer Source

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

xstream.useAttributeFor(Person.class, "age");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download