问题
I am using xstream and trying to serialize a List to XML. I need an output structure like
<Employees>
<Employee></Employee>
<Employee></Employee>
<Employee></Employee>
</Employees>
The object to serialize would be something like an
List<Employee>
or a class Employees. I've tried to create an Employees as
public class Employees extends ArrayList<Employee>(){}
and various other approaches but can't get it to serialize as I need it. Is there an easy way to do such a thing?
My question is similar to XStream - Root as a collection of objects but I'd like to do it without a wrapper object.
回答1:
You're using a list as your root element? You can alias the class. The code below produces the output you're looking for.
public static void main(String[] args) {
List<Employee> employees = new ArrayList<Employee>();
employees.add(new Employee());
employees.add(new Employee());
employees.add(new Employee());
XStream xstream = new XStream();
xstream.alias("Employees", List.class);
System.out.println(xstream.toXML(employees));
}
来源:https://stackoverflow.com/questions/10051501/xstream-how-to-serialize-a-list-to-xml