下面使用的是JDK自帶的類,沒有引用任何第三方jar包。java
Unmarshaller 類使客戶端應用程序可以將 XML 數據轉換爲 Java 內容對象樹。eclipse
備註:marshal(序列化、排列、整理)ide
Marshaller 類使客戶端應用程序可以將 Java 內容樹轉換回 XML 數據。函數
package hb.jaxb; import javax.xml.bind.annotation.XmlRootElement; //一、須要轉換的model對象必定要添加@XmlRootElement註解,其裏面的其餘對象(Cla***oom)則不須要 @XmlRootElement public class Student { private int id; private String name; private int age; private Cla***oom cla***oom; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Cla***oom getCla***oom() { return cla***oom; } public void setCla***oom(Cla***oom cla***oom) { this.cla***oom = cla***oom; } public Student(int id, String name, int age, Cla***oom cla***oom) { super(); this.id = id; this.name = name; this.age = age; this.cla***oom = cla***oom; } //無參夠着函數必定須要,不然JXBContext沒法正常解析。 public Student() { super(); } }
package hb.jaxb; //二、須要轉換的model對象必定要有不帶參數的構造方法,包括該對象裏面引用的對象。 public class Cla***oom { private int id; private String name; private int grade; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getGrade() { return grade; } public void setGrade(int grade) { this.grade = grade; } public Cla***oom(int id, String name, int grade) { super(); this.id = id; this.name = name; this.grade = grade; } public Cla***oom() { super(); } }
package hb.jaxb; import java.io.StringReader; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import org.junit.Test; //Eclipse console //中文亂碼解決 eclipse-->Run-->Run Configuration-->Common--> Console Encoding-->Others-->UTF-8 //參考博文:http://hbiao68.iteye.com/blog/1958413 public class TestJaxb { @Test public void beanToXML() { Cla***oom cla***oom = new Cla***oom(1, "軟件工程", 4); Student student = new Student(101, "張三", 22, cla***oom); try { JAXBContext context = JAXBContext.newInstance(Student.class); Marshaller marshaller = context.createMarshaller(); marshaller.marshal(student, System.out); } catch (JAXBException e) { e.printStackTrace(); } } @Test public void XMLStringToBean(){ String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><student><age>22</age><cla***oom><grade>4</grade><id>1</id><name>軟件工程</name></cla***oom><id>101</id><name>張三</name></student>"; try { JAXBContext context = JAXBContext.newInstance(Student.class); Unmarshaller unmarshaller = context.createUnmarshaller(); Student student = (Student)unmarshaller.unmarshal(new StringReader(xmlStr)); System.out.println(student.getAge()); System.out.println(student.getCla***oom().getName()); } catch (JAXBException e) { e.printStackTrace(); } } }
參考博文:this