1.用JAXB可以实现JAVA对象与XML文件的绑定。可以直接将对象序列化到XML文件中。
需要jaxb-api-2.1.jar支持
2.使用方法:首先定义对象,如下面对象
@XmlRootElement(name = "company")
public class Company {
@XmlElement(name = "employee")
private List employees;
@XmlTransient
public List getEmployees() {
return employees;
}
public void setEmployees(List employees) {
this.employees = employees;
}
public void addEmployee(Employee employee) {
if (employees == null) {
employees = new ArrayList();
}
employees.add(employee);
}
}
其中@XmlRootElement(name = "company")为注释,表示该Company对象对应XML文件中的根节点company,
而@XmlElement(name = "employee")说明对应imployee元素。
@XmlType
public class Employee {
@XmlElement(name = "name")
private String name;
@XmlElement(name = "id")
private String id;
@XmlTransient
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@XmlTransient
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
注意要把@XmlTransient放在get()方法前面,否则可能会出现导致运行报错:
Exception in thread "main" com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException:
2 counts of IllegalAnnotationExceptions
3.需要建一个文件jaxb.index,里面的内容为类的名字,如Company
4.读写XML文件时
JAXBContext jc = JAXBContext.newInstance("test.xml");
Unmarshaller unmarshaller = jc.createUnmarshaller();
Marshaller marshaller = jc.createMarshaller();
// 写入文件,xmlFile为文件名
FileOutputStream fout = new FileOutputStream(xmlFile);
OutputStreamWriter streamWriter = new OutputStreamWriter(fout);
// 文件写入格式
OutputFormat outputFormat = new OutputFormat();
outputFormat.setIndent(4);
outputFormat.setLineSeparator(System.getProperty("line.separator"));
XMLSerializer xmlSerializer = new XMLSerializer(streamWriter, outputFormat);
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
marshaller.marshal(company, xmlSerializer);
// 读取文件
Company company = (Company) unmarshaller.unmarshal(xmlFile);