JAXB操作xml示例(Java与xml之间映射)

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
这是标题

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值