1.Java对象转化成XML(marshal)
public void java2xml ()
{
File file = new File("c:/demo1.xml");
JAXBContext context;
try
{
context = JAXBContext.newInstance(Article.class);
Marshaller marshaller = context.createMarshaller();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日_HH时mm分ss秒");
Article article = new Article();
article.setAuthor("李佳龙");
article.setDate(sdf.format(new Date()));
article.setEmail("xinloveminnie@qq.com");
article.setTitle("这是标题");
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT , true);// 格式化输出
marshaller.setProperty(Marshaller.JAXB_ENCODING , "UTF-8");// 设置输出编码,默认为UTF-8
marshaller.marshal(article , file);
}
catch (Exception e)
{
e.printStackTrace();
}
}
生成的XML文件内容:
<xml version="1.0" encoding="UTF-8" standalone="yes">
<article>
<author>李佳龙</author>
<date>2011年04月10日_20时11分42秒</date>
<email>xinloveminnie@qq.com</email>
<title>这是标题</title>
</article>
2.XML转为JAVA对象(unmarshal)
public void xml2Java ()
{
File xnlFile = new File("c:/demo1.xml");
JAXBContext context;
try
{
context = JAXBContext.newInstance(Article.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
Article article = (Article) unmarshaller.unmarshal(xnlFile);
System.out.println(article.getAuthor());
System.out.println(article.getDate());
System.out.println(article.getEmail());
System.out.println(article.getTitle());
}
catch (Exception e)
{
e.printStackTrace();
}
}
输出:
李佳龙
2011年04月10日_20时11分42秒
xinloveminnie@qq.com
这是标题