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 toXML
method as below:
<Person>
<firstname>David</firstname>
<lastname>Goswami</lastname>
<age>34</age>
</Person>
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:
<Person>
<firstname age="34">David</firstname>
<lastname>Goswami</lastname>
</Person>
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");