webservice04#对象与xml转换-jaxb

1,Student类

package com.yangw.xml;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement //作为根节点的元素需要设置这个注解
public class Student {

    private int id;
    private String name;
    private int age;
    private 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;
    }   
    ....  get set ...  
}

2, Classroom对象

package com.yangw.xml;

public class Classroom {

    private  int id;
    private String name;    //班级名称
    private int grade;        //年级
    
    public Classroom(int id, String name, int grade) {
        super();
        this.id = id;
        this.name = name;
        this.grade = grade;
    }
    
    public Classroom() {
        super();
    }  
    ... get  set  ...
}

3, 测试类,对象与xml互转

package com.yangw.xml;

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;

public class TestJaxb {

    /**
     * 编排:对象转成xml
     */
    @Test
    public void test01() {
        
        try {
            JAXBContext ctx=JAXBContext.newInstance(Student.class);
            Marshaller marshaller=ctx.createMarshaller();
            
            Student stu=new Student(1,"张",20,new Classroom(1,"软件工程01",2008));
            //参数: 对象,输出流
            marshaller.marshal(stu, System.out);
        } catch (JAXBException e) {
            
            e.printStackTrace();
        }
    }

    /**
     * 反编排:xml转成对象
     */
    @Test
    public void test02() {
        
        try {
            JAXBContext ctx=JAXBContext.newInstance(Student.class);
            Unmarshaller um=ctx.createUnmarshaller();
            
            String xml="<?xml version=‘1.0‘ encoding=‘UTF-8‘ standalone=‘yes‘?><student><age>20</age><classroom><grade>2008</grade><id>1</id><name>软件工程01</name></classroom><id>1</id><name>张</name></student>";
            //参数: 对象,输出流
            Student stu=(Student)um.unmarshal(new StringReader(xml));
            System.out.println(stu.getName()+"-->"+stu.getClassroom().getName());
        } catch (JAXBException e) {
            
            e.printStackTrace();
        }
    }

}

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。