源码下载:链接:http://pan.baidu.com/s/1ntL1a7R 密码: rwp1
本文主要讲述:使用jaxb完成对象和xml之间的转换
TestJava2xml.java如下所示:
package com.tgb.jaxb.v1; import java.io.StringReader; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import org.junit.Test; /** * 通过Java和XML之间相互转换 * @author 赵栗婧 * @version 1.0.0 , 2015年6月25日 下午12:12:16 */ public class TestJava2xml { // 测试:Java文件转化为Xml文件 @Test public void testJava2Xml() { try { JAXBContext ctx = JAXBContext.newInstance(Student.class); // 用于Java文件转化为Xml文件的类 Marshaller marshaller = ctx.createMarshaller(); Student student = new Student(1001, "赵栗婧", 20, new Classroom(10, "10级生命科学与工程", 2010)); marshaller.marshal(student, System.out); } catch (JAXBException e) { e.printStackTrace(); } } // 测试Xml文件转化为Java文件 @Test public void testXml2Java() { String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" + "<student>" + "<age>20</age>" + "<classroom>" + "<grade>2010</grade>" + "<id>10</id>" + "<name>10级生命科学与工程</name>" + "</classroom>" + "<id>1001</id>" + "<name>赵栗婧</name>" + "</student>"; try { JAXBContext ctx = JAXBContext.newInstance(Student.class); // 用于Xml文件转化为Java文件的类 Unmarshaller um = ctx.createUnmarshaller(); Student student = (Student) um.unmarshal(new StringReader(xml)); System.out.println(student.getName() + "," + student.getClassroom().getName()); } catch (JAXBException e) { e.printStackTrace(); } } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-11-09 10:44:01