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;}@Overridepublic 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]
?下来我们再深入些,看看其他情况下的处理,请看下节
?