有时候,我们需要把Java对象转换成XML文件。这时可以用JAXB来实现。(JDK1.6及以后的版本无需导入依赖包,因为已经包含在JDK里了)
假如某个公司有许多部门,每个部门有许多职员,我们可以这样来设计简单的bean对象。
[java] view plain copy @XmlRootElement(name="department") public class Department { private String name; //部门名称 private List<Staff> staffs; // 其实staff是单复同型,这里是加's'是为了区别staff 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; } }
[java] view plain copy @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字符串。
[java] view plain copy public class Main { public static void main(String[] args) throws Exception { JAXBContext context = JAXBContext.newInstance(Department.class,Staff.class); // 获取上下文对象 Marshaller marshaller = context.createMarshaller(); // 根据上下文获取marshaller对象 marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); // 设置编码字符集 marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // 格式化XML输出,有分行和缩进 marshaller.marshal(getSimpleDepartment(),System.out); // 打印到控制台 ByteArrayOutputStream baos = new ByteArrayOutputStream(); marshaller.marshal(getSimpleDepartment(), baos); String xmlObj = new String(baos.toByteArray()); // 生成XML字符串 System.out.println(xmlObj); } /** * 生成一个简单的Department对象 * @return */ 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; } }
控制台打印信息:
[plain] view plain copy <?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转换成对象。
转载于:https://www.cnblogs.com/qi-dian-ao/p/8470764.html
相关资源:XML转换为JAVA对象的方法