xml與java物件之間的相互轉化
阿新 • • 發佈:2019-02-16
Java和xml的互相轉換,依靠強大的JAXBContext可以輕鬆實現。
下面通過一個簡單案例學習一下JAXBContext
首先準備好一個JavaBean供實驗:
注意
1、類檔案註解:@XmlRootElement不可缺少
2、2個Student的構造方法不能少
- @XmlRootElement
- publicclass Student {
- private String name;
- private String width;
- private String height;
- privateint age;
- public Student(String name, String width, String height,
- super();
- this.name = name;
- this.width = width;
- this.height = height;
- this.age = age;
- }
- public String getName() {
- return name;
- }
- publicvoid setName(String name) {
- this.name = name;
- }
- public String getWidth() {
- return width;
- }
- publicvoid setWidth(String width) {
- this.width = width;
- }
- public String getHeight() {
- return height;
- }
- publicvoid setHeight(String height) {
- this.height = height;
- }
- publicint getAge() {
- return age;
- }
- publicvoid setAge(int age) {
- this.age = age;
- }
- public Student() {
- super();
- }
- }
JavaToXml:
- @Test
- publicvoid test01(){
- try {
- JAXBContext jc = JAXBContext.newInstance(Student.class);
- Marshaller ms = jc.createMarshaller();
- Student st = new Student("zhang", "w", "h", 11);
- ms.marshal(st, System.out);
- } catch (JAXBException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
XmlToJava
- //xml轉換Java
- @Test
- publicvoid test02() throws JAXBException{
- String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><student><age>11</age><height>h</height><name>zhang</name><width>w</width></student>";
- JAXBContext jc = JAXBContext.newInstance(Student.class);
- Unmarshaller unmar = jc.createUnmarshaller();
- Student stu = (Student) unmar.unmarshal(new StringReader(xml));
- System.out.println(stu.getName());
- }