天天看点

java对象和xml对象的相互转换

java中提供了相关的api,jaxb可以实现java对象与xml对象相互转换,话不多说,下面以实际的例子来说明两者对象间的转换:

1.java对象转换为xml对象称为Marshall(编排)

Student实体类:

package com.jaxb;

/*
 * author:lc_kykz
 * Description:Student Entity
 */
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Student {
	
	private String studentId;

	private String studentName;

	private String studentSex;

	//空构造函数,必须要写
	public Student() {
		super();
	}

	public Student(String studentId, String studentName, String studentSex) {
		super();
		this.studentId = studentId;
		this.studentName = studentName;
		this.studentSex = studentSex;
	}

	public String getStudentId() {
		return studentId;
	}

	public String getStudentName() {
		return studentName;
	}

	public String getStudentSex() {
		return studentSex;
	}

	public void setStudentId(String studentId) {
		this.studentId = studentId;
	}

	public void setStudentName(String studentName) {
		this.studentName = studentName;
	}

	public void setStudentSex(String studentSex) {
		this.studentSex = studentSex;
	}
}
           

junit测试方法:

<span style="white-space:pre">	</span>@Test
	public void test_Student() throws Exception{
		//创建一个JAXBContent对象,单例模式创建,
		JAXBContext ctx = JAXBContext.newInstance(Student.class);
		
		//创建一个编排
		Marshaller cm = ctx.createMarshaller();
		
		//创建一个Student实例
		Student student = new Student("001", "张三", "男");
		
		//将Student对象进行编排
		cm.marshal(student, System.out);
	}
           

测试方法输出结果:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><student><studentId>001</studentId><studentName>张三</studentName><studentSex>男</studentSex></student>
           

2.xml对象转换为java对象称为unMarshall(反编排)

<span style="white-space:pre">	</span>@Test
	public void test() throws Exception {
		//定义一个xml格式的字符串
		String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><student><studentId>001</studentId><studentName>张三</studentName><studentSex>男</studentSex></student>";

		// 创建一个JAXBContent对象,单例模式创建,
		JAXBContext ctx = JAXBContext.newInstance(Student.class);

		// 创建一个反编排
		Unmarshaller um = ctx.createUnmarshaller();

		// 将xml对象进行反编排
		Student student = (Student)um.unmarshal(new StringReader(xml));
		
		System.out.println("<span style="font-family: Arial, Helvetica, sans-serif;">Student的ID为:</span>" + student.getStudentId());
	}
           

测试方法输出结果:

Student的ID为:001

java对象和xml对象相互转换就是这么的简单易懂,只需要几行核心代码就可以解决!