需要jaxb
@XmlRootElement(name =
public class Company {
@XmlElement(name =
private List<Employee> employees;
@XmlTransient
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this
}
public void addEmployee(Employee employee) {
if (employees == null) {
employees = new ArrayList<Employee>();
}
employees
}
}
其中@XmlRootElement(name =
而@XmlElement(name =
@XmlType
public class Employee {
@XmlElement(name =
private String name;
@XmlElement(name =
private String id;
@XmlTransient
public String getId() {
return id;
}
public void setId(String id) {
this
}
@XmlTransient
public String getName() {
return name;
}
public void setName(String name) {
this
}
}
注意要把@XmlTransient放在get()方法前面
Exception in thread
JAXBContext jc = JAXBContext
Unmarshaller unmarshaller = jc
Marshaller marshaller = jc
// 寫入文件
FileOutputStream fout = new FileOutputStream(xmlFile);
OutputStreamWriter streamWriter = new OutputStreamWriter(fout);
// 文件寫入格式
OutputFormat outputFormat = new OutputFormat();
outputFormat
outputFormat
XMLSerializer xmlSerializer = new XMLSerializer(streamWriter
marshaller
marshaller
// 讀取文件
Company company = (Company) unmarshaller
From:http://tw.wingwit.com/Article/program/Java/hx/201311/26719.html