首页 > 代码库 > Java对象与xml文件互转
Java对象与xml文件互转
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()); } }
本文出自 “阿凡达” 博客,请务必保留此出处http://shamrock.blog.51cto.com/2079212/1545229
Java对象与xml文件互转
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。