JAXB(Java Architecture for XML Binding) 是一個業界的標準,是一項能夠根據XML Schema產生Java類的技術。該過程當中,JAXB也提供了將XML實例文檔反向生成Java對象樹的方法,並能將Java對象樹的內容從新寫到XML實例文檔。從另外一方面來說,JAXB提供了快速而簡便的方法將XML模式綁定到Java表示,從而使得Java開發者在Java應用程序中能方便地結合XML數據和處理函數。java
程序中簡單使用app
/** * Created by lv on 2016/4/3. */ public class Person { private String name; private LocalDate birthday; public String getName() { return name; } public void setName(String name) { this.name = name; } //注意,此處使用自定義適配器來解析date類型的字段 @XmlJavaTypeAdapter(LocalDateAdapter.class) public LocalDate getBirthday() { return birthday; } public void setBirthday(LocalDate birthday) { this.birthday = birthday; } } @XmlRootElement(name = "persons") public class PersonListWrapper { private List<Person> persons; @XmlElement(name = "person") public List<Person> getPersons() { return persons; } public void setPersons(List<Person> persons) { this.persons = persons; } } //定義適配器 /** * Created by lv on 2016/4/3. */ public class LocalDateAdapter extends XmlAdapter<String,LocalDate>{ @Override public LocalDate unmarshal(String v) throws Exception { return LocalDate.parse(v); } @Override public String marshal(LocalDate v) throws Exception { return v.toString(); } }
程序中使用:ide
/** * 從xml文件中加載數據 * @param file */ public void loadPersonDataFromFile(File file) { try { JAXBContext jaxbContext = JAXBContext.newInstance(PersonListWrapper.class); Unmarshaller um = jaxbContext.createUnmarshaller(); PersonListWrapper wrapper = (PersonListWrapper) um.unmarshal(file); } catch (JAXBException e) { e.printStackTrace(); } } /** * 保存數據到xml文件中 * @param file */ public void savePersonDataToFile(File file){ try { JAXBContext context = JAXBContext .newInstance(PersonListWrapper.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); PersonListWrapper wrapper = new PersonListWrapper(); wrapper.setPersons(personData); m.marshal(wrapper, file); } catch (JAXBException e) { e.printStackTrace(); } }