import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Area {
private String areaCode;
private String areaName;
private int areaLevel;
private int subAreaNum;
@XmlAttribute
public String getAreaCode() {
return areaCode;
}
public void setAreaCode(String areaCode) {
this.areaCode = areaCode;
}
@XmlAttribute
public String getAreaName() {
return areaName;
}
public void setAreaName(String areaName) {
this.areaName = areaName;
}
@XmlAttribute
public int getAreaLevel() {
return areaLevel;
}
public void setAreaLevel(int areaLevel) {
this.areaLevel = areaLevel;
}
@XmlAttribute
public int getSubAreaNum() {
return subAreaNum;
}
public void setSubAreaNum(int subAreaNum) {
this.subAreaNum = subAreaNum;
}
}import java.io.FileWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
public class Test01 {
public static void main(String[] args) throws Exception {
JAXBContext context = JAXBContext.newInstance(Area.class);
Marshaller m = context.createMarshaller();
Area area = new Area();
area.setAreaCode("420000000000");
area.setAreaLevel(2);
area.setAreaName("湖北");
area.setSubAreaNum(14);
FileWriter fw = new FileWriter("E:\\area.xml");
m.marshal(area, fw);
//<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
//
// 下面代码演示将上面生成的xml转换为对象。
//这段代码来自新浪博客,未测试
//FileReader fr = new FileReader("E:\\test\\person.xml");
//Unmarshaller um = context.createUnmarshaller();
//Person p2 = (Person) um.unmarshal(fr);
//System.out.println("Country:" + p2.getAddress().getCountry());
}
}
原文:http://shamrock.blog.51cto.com/2079212/1545229