用JAXB可以实现JAVA对象与XML文件的绑定可以直接将对象序列化到XML文件中
需要jaxbapijar支持
使用方法首先定义对象如下面对象
@XmlRootElement(name = company)
public class Company {
@XmlElement(name = employee)
private List<Employee> employees;
@XmlTransient
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
thisemployees = employees;
}
public void addEmployee(Employee employee) {
if (employees == null) {
employees = new ArrayList<Employee>();
}
employeesadd(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) {
thisid = id;
}
@XmlTransient
public String getName() {
return name;
}
public void setName(String name) {
thisname = name;
}
}
注意要把@XmlTransient放在get()方法前面否则可能会出现导致运行报错
Exception in thread main comsunxmlinternalbindvruntimeIllegalAnnotationsException:
counts of IllegalAnnotationExceptions
需要建一个文件jaxbindex里面的内容为类的名字如Company
读写XML文件时
JAXBContext jc = JAXBContextnewInstance(testxml);
Unmarshaller unmarshaller = jccreateUnmarshaller();
Marshaller marshaller = jccreateMarshaller();
// 写入文件xmlFile为文件名
FileOutputStream fout = new FileOutputStream(xmlFile);
OutputStreamWriter streamWriter = new OutputStreamWriter(fout);
// 文件写入格式
OutputFormat outputFormat = new OutputFormat();
outputFormatsetIndent();
outputFormatsetLineSeparator(SystemgetProperty(lineseparator));
XMLSerializer xmlSerializer = new XMLSerializer(streamWriter outputFormat);
marshallersetProperty(MarshallerJAXB_ENCODING UTF);
marshallermarshal(company xmlSerializer);
// 读取文件
Company company = (Company) unmarshallerunmarshal(xmlFile);