JAXB学习笔记(三)
想知道生成的xml节点名字怎么换吗,如果你看下annotation @XmlElement的源码就明白了,看这个例子
Java代码
package cn.uyunsky.blog.xml.demo3;
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.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
* <p>把节点名字换换</p>
*/
@XmlRootElement(name="PERSION")
@XmlAccessorType(XmlAccessType.FIELD)
public class Persion {
@XmlElement(name="USER_ID")
private Integer userid;
@XmlElement(name="USER_NAME")
private String username;
@XmlElement(name="BIRTHDAY")
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代码
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<PERSION>
<USER_ID>112</USER_ID>
<USER_NAME>就不告诉你</USER_NAME>
<BIRTHDAY>2011-09-28T11:29:28.375+08:00</BIRTHDAY>
</PERSION>
Persion [userid=112, username=就不告诉你, birthday=Wed Sep 28 11:29:28 CST 2011]
JAXB转换方式的实现通过annotation来处理,因此我们想要什么功能可以仔细研究下javax.xml.bind.annotation每个注释的意义,语感好的通过类名就能猜到了
java与E文一样需要好的语感的~
作者“有云的天空”
补充:软件开发 , Java ,