JAXB转换xml和JavaBean
鼓捣了一番,一开始各种出错,终于得以解决问题。下面晒晒吧(例子是存储学生) 学生类: import java.util.ArrayList; import java.util.ArrayList; import java.io.File; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; public class testmain { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub student s = new student(); s.name = "dang"; s.age = "18"; s.addscore("100"); s.addscore("90"); student s2 = new student(); s2.name = "cha"; s2.age = "14"; s.addscore("100"); s.addscore("95"); studnets ss = new studnets(); ss.addstu(s); ss.addstu(s2); try { javatoxml(ss,new File("a.xml")); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } File f=new File("a.xml"); try { studnets crb = (studnets) xmltojava(studnets.class,f); System.out.println(crb.students.get(0).name); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("不行喔"); } /* * 结果: * <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <students> <stu> <name>dang</name><age>18</age> <score>100</score><score>90</score> <score>100</score><score>95</score> </stu> <stu> <name>cha</name> <age>14</age> </stu> </students> */ } public static Object xmltojava(Class cls,File file) throws Exception{ JAXBContext ctx=JAXBContext.newInstance(cls); //JAXBContext可以创建 Unmarshallers(将XML解析为Java对象) Unmarshaller us=ctx.createUnmarshaller(); return us.unmarshal(file); } //*************JavaBeanàXML*********************** public static void javatoxml(Object obj,File file) throws Exception{ JAXBContext ctx=JAXBContext.newInstance(obj.getClass()); //JAXBContext可以创建Marshallers(将Java对象转换成XML) Marshaller mar=ctx.createMarshaller(); mar.marshal(obj,file); } } 好了,运行就行了,打完收工。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |