jaxb读写xml小例子
使用maven构建工程,在pom.xml加入如下依赖: <dependency> //一个Person类: package com.mycomp.jaxb; package com.mycomp.jaxb; import java.io.File; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller;
public class App { //写入xml的方法 try { JAXBContext cxt = JAXBContext.newInstance(Person.class); Marshaller marshaller = cxt.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_ENCODING,"UTF-8");// 编码格式 marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);// 是否格式化生成的xml串 marshaller.setProperty(Marshaller.JAXB_FRAGMENT,false);// 默认false表示xml指令存在 marshaller.marshal(person,file); } catch (JAXBException e) { e.printStackTrace(); } } //读取xml的方法 private static void readXml(File file){ try { JAXBContext cxt = JAXBContext.newInstance(Person.class); Unmarshaller unmarshaller = cxt.createUnmarshaller(); Person person = (Person)unmarshaller.unmarshal(file); if (person != null) { System.out.println(person.getName()); System.out.println(person.getAge()); System.out.println(person.getSex()); } } catch (JAXBException e) { e.printStackTrace(); } } public static void main( String[] args ){ File file = new File("d:/test.xml"); Person person = new Person("张三",20,"男"); writeXml(person,file); readXml(file); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |