JAXB学习笔记(一)

项目为了进行xml与java bean的互转,参考了各位网友的推荐,最后选型为JAXB,闲暇之余整理了一下笔记。废话不多说,上代码

当然JDK至少是1.6的啊,好处是再不需要其他的包

 

这里构造一个persion对象,很简单,先来看第一个简单的例子,进入到JAXB的世界

 

package cn.uyunsky.blog.xml.demo1;

import java.io.StringReader;
import java.io.StringWriter;
import java.util.Date;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;


/**
 * <p>先来个简单的</p>
 */
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Persion {

	private Integer userid;
	private String username;
	private Date birthday;

	public Integer getUserid() {
		return userid;
	}

	public void setUserid(Integer userid) {
		this.userid = userid;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("Persion [userid=");
		builder.append(userid);
		builder.append(", username=");
		builder.append(username);
		builder.append(", birthday=");
		builder.append(birthday);
		builder.append("]");
		return builder.toString();
	}

	public static void main(String[] args) {
		try {
			JAXBContext jaxbContext = JAXBContext.newInstance(Persion.class);
			Persion persion = new Persion();

			persion.setUserid(112);
			persion.setUsername("就不告诉你");
			persion.setBirthday(new Date());

			Marshaller marshaller = jaxbContext.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

			StringWriter writer = new StringWriter();
			marshaller.marshal(persion, writer);
			String xml = writer.getBuffer().toString();
			System.out.println(xml);

			Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
			Object bean = unmarshaller.unmarshal(new StringReader(xml));
			System.out.println(bean);

		} catch (JAXBException e) {
			e.printStackTrace();
		}
	}

}

 

 执行结果

 

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<persion>
    <userid>112</userid>
    <username>就不告诉你</username>
    <birthday>2011-09-28T11:06:29.734+08:00</birthday>
</persion>

Persion [userid=112, username=就不告诉你, birthday=Wed Sep 28 11:06:29 CST 2011]

 下来我们再深入些,看看其他情况下的处理,请看下节

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值