JDK自帶XML和java物件相互轉換
阿新 • • 發佈:2019-02-05
下面使用的是JDK自帶的類,沒有引用任何第三方jar包。
Unmarshaller 類使客戶端應用程式能夠將 XML 資料轉換為 Java 內容物件樹。
備註:marshal(序列化、排列、整理)
Marshaller 類使客戶端應用程式能夠將 Java 內容樹轉換回 XML 資料。
package hb.jaxb; import javax.xml.bind.annotation.XmlRootElement; //1、需要轉換的model物件一定要新增@XmlRootElement註解,其裡面的其他物件(Classroom)則不需要 @XmlRootElement public class Student { private int id; private String name; private int age; private Classroom classroom; 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 Classroom getClassroom() { return classroom; } public void setClassroom(Classroom classroom) { this.classroom = classroom; } public Student(int id, String name, int age, Classroom classroom) { super(); this.id = id; this.name = name; this.age = age; this.classroom = classroom; } //無參夠著函式一定需要,否則JXBContext無法正常解析。 public Student() { super(); } }
package hb.jaxb; //2、需要轉換的model物件一定要有不帶引數的構造方法,包括該物件裡面引用的物件。 public class Classroom { 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 Classroom(int id, String name, int grade) { super(); this.id = id; this.name = name; this.grade = grade; } public Classroom() { 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() { Classroom classroom = new Classroom(1, "軟體工程", 4); Student student = new Student(101, "張三", 22, classroom); 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><classroom><grade>4</grade><id>1</id><name>軟體工程</name></classroom><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.getClassroom().getName()); } catch (JAXBException e) { e.printStackTrace(); } } }
參考博文: