有时候,我们需要把Java对象转换成XML文件。这时可以用JAXB来实现。(JDK1.6及以后的版本无需导入依赖包,因为已经包含在JDK里了)
假如某个公司有许多部门,每个部门有许多职员,我们可以这样来设计简单的bean对象。
- @XmlRootElement(name="department")
- public class Department {
-
- private String name;
- private List<Staff> staffs;
-
- public String getName() {
- return name;
- }
- @XmlAttribute
- public void setName(String name) {
- this.name = name;
- }
- public List<Staff> getStaffs() {
- return staffs;
- }
- @XmlElement(name="staff")
- public void setStaffs(List<Staff> staffs) {
- this.staffs = staffs;
- }
- }
- @XmlRootElement(name="staff")
- public class Staff {
-
- private String name;
- private int age;
- private boolean smoker;
-
- public String getName() {
- return name;
- }
- @XmlElement
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- @XmlElement
- public void setAge(int age) {
- this.age = age;
- }
- public boolean isSmoker() {
- return smoker;
- }
- @XmlAttribute
- public void setSmoker(boolean smoker) {
- this.smoker = smoker;
- }
- }
下面将生成一个简单的对象,并转换成XML字符串。
- public class Main {
-
- public static void main(String[] args) throws Exception {
-
- JAXBContext context = JAXBContext.newInstance(Department.class,Staff.class);
- Marshaller marshaller = context.createMarshaller();
-
- marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
- marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
-
- marshaller.marshal(getSimpleDepartment(),System.out);
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- marshaller.marshal(getSimpleDepartment(), baos);
- String xmlObj = new String(baos.toByteArray());
- System.out.println(xmlObj);
- }
-
-
- private static Department getSimpleDepartment() {
- List<Staff> staffs = new ArrayList<Staff>();
-
- Staff stf = new Staff();
- stf.setName("周杰伦");
- stf.setAge(30);
- stf.setSmoker(false);
- staffs.add(stf);
- stf.setName("周笔畅");
- stf.setAge(28);
- stf.setSmoker(false);
- staffs.add(stf);
- stf.setName("周星驰");
- stf.setAge(40);
- stf.setSmoker(true);
- staffs.add(stf);
-
- Department dept = new Department();
- dept.setName("娱乐圈");
- dept.setStaffs(staffs);
-
- return dept;
- }
- }
控制台打印信息:
- <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
- <department name="娱乐圈">
- <staff smoker="true">
- <age>40</age>
- <name>周星驰</name>
- </staff>
- <staff smoker="true">
- <age>40</age>
- <name>周星驰</name>
- </staff>
- <staff smoker="true">
- <age>40</age>
- <name>周星驰</name>
- </staff>
- </department>
注意到,我们可以用Marshaller.marshal方法将对象转换成xml文件,也可以用UnMarshaller.unmarshal将xml转换成对象。
Java对象和XML转换
原文:http://www.cnblogs.com/doudouxiaoye/p/5693441.html