/**
* 员工对象
* @author Administrator
*
*/
public class Employee {
private int id;
private String name;
private int age;
private String sex;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
package com.mashen.servlet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import com.thoughtworks.xstream.XStream;
/**
*部门 对象
* @author Administrator
*
*/
public class Department {
private int code;
private String name;
private Set<Employee> Employee ;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Employee> getEmployee() {
return Employee;
}
public void setEmployee(Set<Employee> employee) {
Employee = employee;
}
/**
* 对XStream的实例应用
* 将对象转换成XML文件格式
* @param args
*/
public static void main(String[] args) {
Employee ely1 = new Employee();
ely1.setId(1);
ely1.setName("小明");
ely1.setAge(20);
ely1.setSex("男");
Department depm = new Department();
depm.setCode(1);
depm.setName("技术部");
Set<Employee> emplySet = new HashSet<Employee>();
emplySet.add(ely1);
depm.setEmployee(emplySet);
XStream xst = new XStream();
xst.alias("employee", Employee.class);//起别名映射
xst.alias("department", Department.class);
String xml = xst.toXML(depm);
Department dept = (Department) xst.fromXML(xml);
System.out.println(dept);
Set<Employee> s = depm.getEmployee();
for (Iterator<Employee> iterator = s.iterator(); iterator.hasNext();) {
Employee obj = (Employee) iterator.next();
System.out.println(obj.getId()+'\n'+obj.getName()+'\n'+obj.getAge()+'\n'+obj.getSex());
}
}
}