xstream, how to serialize a list to xml

给你一囗甜甜゛ 提交于 2019-12-12 00:37:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!