WebService(2)-XML系列之Java和Xml之间相互转换
源代码下载:链接: http://pan.baidu.com/s/1ntL1a7R password: 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级生命科学与project", 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级生命科学与project</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(); } } }