JAXB(xml和对象的转换)

1、编排(将java转换成xml)

2、反编排(将xml转换成java)

首先先编排(要在编排的类上面用一个注解)

            @XmlRootElement
            JAXBContext ctx=JAXBContext.newInstance(Student.class);//jdk1.6自带
            Student stu=new Student(1,"李阳","24",new ClassRoom(10,"13信息与计算科学",2013));
            Marshaller marshaller=ctx.createMarshaller();//编排
            marshaller.marshal(stu, System.out);

反编排

               String xml="<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><student><age>24</age><classroom><gra                       de>2013</grade><id>10</id><name>13信息与计算科学</name></classroom><id>1</id><name>李阳</name></student>";
               JAXBContext ctx=JAXBContext.newInstance(Student.class);//jdk1.6自带
               Unmarshaller unmarshaller=ctx.createUnmarshaller();//反编排
               Student stu=(Student) unmarshaller.unmarshal(new StringReader(xml));
               System.out.println(stu.getName());

 

posted @ 2014-01-24 11:06  离子  阅读(214)  评论(0编辑  收藏  举报