加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

XML:使用JAXB完成JavaBean和xml的转化

发布时间:2020-12-16 06:00:10 所属栏目:百科 来源:网络整理
导读:使用JAXB完成java和xml的转化【需要在你的实体类上添加 @XmlRootElement 】 public class Classroom { privateint id; privateString name; privateint grade; publicClassroom(int id,String name,int grade) { super(); this.id= id; this.name= name; thi

使用JAXB完成java和xml的转化【需要在你的实体类上添加 @XmlRootElement

public class Classroom {

privateint id;

privateString name;

privateint grade;

publicClassroom(int id,String name,int grade) {

super();

this.id= id;

this.name= name;

this.grade= grade;

}

publicClassroom() {

super();

//TODO Auto-generated constructor stub

}

}

@XmlRootElement

public class Student {

privateint id;

privateString name;

privateint age;

private Classroom classroom;

publicStudent(int id,int age,Classroom classroom) {

super();

this.id= id;

this.name= name;

this.age= age;

this.classroom= classroom;

}

publicStudent() {

super();

}

}

@Test【对象转换为XML】

publicvoid test01() {

try{

JAXBContextctx = JAXBContext.newInstance(Student.class);

Marshallermarshaller = ctx.createMarshaller();

Studentstu = new Student(1,"张三",21,new Classroom(1,"10计算机应用技术",2010));

marshaller.marshal(stu,System.out);

}catch (JAXBException e) {

e.printStackTrace();

}

}

@Test【XML转换为对象】

publicvoid test02() {

try{

Stringxml = "<?xml version="1.0" encoding="UTF-8"standalone="yes"?><student><age>21</age><classroom><grade>2010</grade><id>1</id><name>10计算机应用技术</name></classroom><id>1</id><name>张三</name></student>";

JAXBContextctx = JAXBContext.newInstance(Student.class);

Unmarshallerum = ctx.createUnmarshaller();

Studentstu = (Student)um.unmarshal(new StringReader(xml));

System.out.println(stu.getName()+","+stu.getClassroom().getName());

}catch (JAXBException e) {

e.printStackTrace();

}

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读