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"?> //<area subAreaNum="14" areaName="湖北" areaLevel="2" areaCode="420000000000"/> // 下面代码演示将上面生成的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()); } }
在servlet中向浏览器打印xml数据时容易出现中文乱码,解决方案如下
response.setCharacterEncoding("UTF-8"); response.setHeader("content-type","text/html;charset=UTF-8"); PrintWriter out=response.getWriter();
一定要先设置字符集