梦幻之旅

DEBUG - 天道酬勤

   :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  671 随笔 :: 6 文章 :: 256 评论 :: 0 Trackbacks
package test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class HelloWorld {

  
private String hello;
  
private Integer world;

  
public String getHello() {
    
return hello;
  }


  
public void setHello(String hello) {
    
this.hello = hello;
  }


  
public Integer getWorld() {
    
return world;
  }


  
public void setWorld(Integer world) {
    
this.world = world;
  }


  
public String toString() {
    
return hello + "-" + world;
  }


  
public static void main(String[] args) throws Exception {

    
// Set up file and JAXB context
    final File file = new File("hello.xml");
    
    JAXBContext context 
= JAXBContext.newInstance(HelloWorld.class);

    
// Creates a HelloWorld object
    HelloWorld hw = new HelloWorld();
    hw.setHello(
"Hello !!!");
    hw.setWorld(
1234);

    
// From a HelloWorld object creates a hello.xml file
    Marshaller m = context.createMarshaller();
    StringWriter sw 
= new StringWriter();
    m.marshal(hw, sw);
    System.out.println(sw.toString());
    m.marshal(hw, 
new FileOutputStream(file));

    
// From the hello.xml file creates a HelloWorld object
    Unmarshaller um = context.createUnmarshaller();
    StringReader sr 
= new StringReader(sw.toString());
    HelloWorld hw2 
= (HelloWorld) um.unmarshal(sr);
    System.out.println(hw2);

  }

}


posted on 2010-09-25 18:25 HUIKK 阅读(191) 评论(0)  编辑  收藏 所属分类: Java

只有注册用户登录后才能发表评论。


网站导航: