private static void java2XmlTest() { StudentInfo student = new StudentInfo(); student.setId(1); student.setName("Hello World!"); student.setAge(26); student.setAddress("深圳市福田区新洲街湖北大厦"); student.setBirthday(new Date()); student.setCreateTime(new Date()); student.setEmail("*****@*****.**"); student.setPassword("123465"); student.setSex(1); try { // File file=new File("D:\\HelloWorld.xml"); // //初始化JAXBContext.JAXBContext类提供的JAXB API的客户端的入口点。 // //它提供一个抽象的用于管理XML / Java绑定的必要信息,以实现JAXB绑定框架行动:解组,编组和验证。 // JAXBContext jc=JAXBContext.newInstance(StudentInfo.class); // //将Java对象Marshal成XML内容的Marshal的初始化设置. // Marshaller jaxbMarshaller=jc.createMarshaller(); // //output // jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // jaxbMarshaller.marshal(student, file); // jaxbMarshaller.marshal(student, System.out);//控制台输出 File marshalFile = marshal(student, "D:\\HelloWorld.xml"); if (marshalFile != null) { System.out.println("marshalFile path : " + marshalFile); } } catch (JAXBException e) { System.out.println("output xml error!"); e.printStackTrace(); } }
private static void xml2JavaTest() { File file = new File("D:\\HelloWorld.xml"); try { // 反着来 // JAXBContext jc=JAXBContext.newInstance(StudentInfo.class); // Unmarshaller unmarshaller=jc.createUnmarshaller(); // StudentInfo cus=(StudentInfo) unmarshaller.unmarshal(file); StudentInfo cus = (StudentInfo) unmarshal(file, StudentInfo.class); System.out.println("data:" + cus); System.out.println("data:" + cus.getId()); System.out.println("data:" + cus.getName()); System.out.println("data:" + cus.getAge()); } catch (JAXBException e) { System.out.println("input xml error!"); e.printStackTrace(); } }