成长

小军军

博客园 首页 联系 订阅 管理

/**
  * 将java对象转换成xml格式
  */
   @Test
   public void JaxbTest(){
    try {
  JAXBContext context=JAXBContext.newInstance(Student.class);
  Marshaller marshaller= context.createMarshaller();
  Student student=new Student(1,"xxx",new ClassRoom(2, "xxx"));
  marshaller.marshal(student, System.out);
 } catch (JAXBException e) {
  e.printStackTrace();
 }
   }

===========================================================================

 /**
    * 将xml格式转换成java
    */
   @Test
   public void JaxbTest1(){
    try {
  String xml="<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><student><classRoom><className>班级</className><classRoomId>2</classRoomId></classRoom><studentId>1</studentId><studentName>xxx军</studentName></student>";
     JAXBContext context=JAXBContext.newInstance(Student.class);
     Unmarshaller unmarshaller=context.createUnmarshaller();
    Student student=(Student)unmarshaller.unmarshal(new StringReader(xml));
    System.out.println(student.getStudentId()+","+student.getStudentName()+","+student.getClassRoom().getClassName());
 } catch (JAXBException e) {
  e.printStackTrace();
 }
   }

 

 

 

posted on 2013-06-17 23:22  houqijun  阅读(185)  评论(0)    收藏  举报