码迷,mamicode.com
首页 > 编程语言 > 详细

JAXB完成XML与Java对象的互转

时间:2014-06-17 23:21:49      阅读:263      评论:0      收藏:0      [点我收藏+]

标签:xml   object   jaxb   

这段时间都老忙了,甚至连周末所有人员都在赶产品的进度,想想连续上12天班,人都有点晕了!到这会儿终于有点时间,所以准备和大家分享一下JAXB,会不会有人觉得有点陌生呢?没事,这里跟大伙儿简单的描述一下:

JAXB(Java Architecture for XML Binding) 是一个业界的标准,是一项可以根据XML Schema产生Java类的技术。该过程中,JAXB也提供了将XML实例文档反向生成Java对象树的方法,并能将Java对象树的内容重新写到XML实例文档。从另一方面来讲,JAXB提供了快速而简便的方法将XML模式绑定到Java表示,从而使得Java开发者在Java应用程序中能方便地结合XML数据和处理函数。

基本知识就说这么多,咱们来点实际的,准备上代码了:

/**
 * @Description: 
 *
 * @Title: Student.java
 * @Package com.joyce.bean
 * @Copyright: Copyright (c) 2014
 *
 * @author Comsys-LZP
 * @date 2014-6-10 下午02:51:41
 * @version V2.0
 */
package com.joyce.bean;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * @Description: 学生实体类
 * 
 * @ClassName: Student
 * @Copyright: Copyright (c) 2014
 * 
 * @author Comsys-LZP
 * @date 2014-6-10 下午02:51:41
 * @version V2.0
 */
@XmlRootElement(name="Student")
public class Student {
	/**
	 * 姓名
	 */
	private String name;
	/**
	 * 性别
	 */
	private String sex;
	/**
	 * 年龄
	 */
	private Integer age;

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name
	 *            the name to set
	 */
	@XmlAttribute
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return the sex
	 */
	public String getSex() {
		return sex;
	}

	/**
	 * @param sex
	 *            the sex to set
	 */
	@XmlElement
	public void setSex(String sex) {
		this.sex = sex;
	}

	/**
	 * @return the age
	 */
	public Integer getAge() {
		return age;
	}

	/**
	 * @param age
	 *            the age to set
	 */
	@XmlElement
	public void setAge(Integer age) {
		this.age = age;
	}

	/**
	 * @param name
	 * @param sex
	 * @param age
	 */
	public Student(String name, String sex, Integer age) {
		super();
		this.name = name;
		this.sex = sex;
		this.age = age;
	}

	/**
	 * 
	 */
	public Student() {
		super();
	}
}

再来一个:
/**
 * @Description: 
 *
 * @Title: Teacher.java
 * @Package com.joyce.bean
 * @Copyright: Copyright (c) 2014
 *
 * @author Comsys-LZP
 * @date 2014-6-10 下午04:29:23
 * @version V2.0
 */
package com.joyce.bean;

import java.util.List;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * @Description: 教师实体类
 * 
 * @ClassName: Teacher
 * @Copyright: Copyright (c) 2014
 * 
 * @author Comsys-LZP
 * @date 2014-6-10 下午04:29:23
 * @version V2.0
 */
@XmlRootElement(name="Teacher")
public class Teacher {
	/**
	 * 姓名
	 */
	private String name;
	/**
	 * 性别
	 */
	private String sex;
	/**
	 * 年龄
	 */
	private Integer age;
	/**
	 * 学生
	 */
	private List<Student> students;

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name
	 *            the name to set
	 */
	@XmlElement
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return the sex
	 */
	public String getSex() {
		return sex;
	}

	/**
	 * @param sex
	 *            the sex to set
	 */
	@XmlElement
	public void setSex(String sex) {
		this.sex = sex;
	}

	/**
	 * @return the age
	 */
	public Integer getAge() {
		return age;
	}

	/**
	 * @param age
	 *            the age to set
	 */
	@XmlElement
	public void setAge(Integer age) {
		this.age = age;
	}

	/**
	 * @return the students
	 */
	public List<Student> getStudents() {
		return students;
	}

	/**
	 * @param students
	 *            the students to set
	 */
	@XmlElement(name="Student")
	public void setStudents(List<Student> students) {
		this.students = students;
	}

	/**
	 * 
	 */
	public Teacher() {
		super();
	}

	/**
	 * @param name
	 * @param sex
	 * @param age
	 */
	public Teacher(String name, String sex, Integer age) {
		super();
		this.name = name;
		this.sex = sex;
		this.age = age;
	}

	/**
	 * @param name
	 * @param sex
	 * @param age
	 * @param students
	 */
	public Teacher(String name, String sex, Integer age, List<Student> students) {
		super();
		this.name = name;
		this.sex = sex;
		this.age = age;
		this.students = students;
	}
}

哈哈,这两个对象一出来,是不是感觉很熟悉呢!对的,我们这里封装对象,为后面实现Java对象和XML的转换提供很好的基础。OK,关键代码要来了哈:
/**
 * @Description: 
 *
 * @Title: JAXBUtil.java
 * @Package com.joyce.util
 * @Copyright: Copyright (c) 2014
 *
 * @author Comsys-LZP
 * @date 2014-6-10 下午02:54:40
 * @version V2.0
 */
package com.joyce.util;

import java.io.ByteArrayOutputStream;
import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
 * @Description:JAXB对象和XML转换util
 * 
 * @ClassName: JAXBUtil
 * @Copyright: Copyright (c) 2014
 * 
 * @author Comsys-LZP
 * @date 2014-6-10 下午02:54:40
 * @version V2.0
 */
public class JAXBUtil {
	
	/**
	 * @Description: 将对象转换为XML
	 *
	 * @param obj
	 * @param beanClass
	 * @return
	 * @throws Exception
	 *
	 * @Title: JAXBUtil.java
	 * @Copyright: Copyright (c) 2014
	 *
	 * @author Comsys-LZP
	 * @date 2014-6-10 下午04:23:45
	 * @version V2.0
	 */
	@SuppressWarnings("unchecked")
	public String objectToXmlStr(Object obj, Class beanClass) throws Exception {
		JAXBContext context = JAXBContext.newInstance(beanClass);
		// 根据上下文获取marshaller对象
		Marshaller marshaller = context.createMarshaller();
		// 设置编码字符集
		marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
		// 格式化XML输出,有分行和缩进
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		// 打印到控制台
		marshaller.marshal(obj, System.out);

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		marshaller.marshal(obj, baos);
		String xmlObj = new String(baos.toByteArray());
		return xmlObj.replace(" standalone=\"yes\"", "");
	}
	
	/**
	 * @Description: 将对象转换为XML并且写入文件
	 *
	 * @param obj
	 * @param beanClass
	 * @param file
	 * @throws Exception
	 *
	 * @Title: JAXBUtil.java
	 * @Copyright: Copyright (c) 2014
	 *
	 * @author Comsys-LZP
	 * @date 2014-6-10 下午04:24:13
	 * @version V2.0
	 */
	@SuppressWarnings("unchecked")
	public void objectToXmlStr(Object obj, Class beanClass, File file) throws Exception {
		JAXBContext context = JAXBContext.newInstance(beanClass);
		// 根据上下文获取marshaller对象
		Marshaller marshaller = context.createMarshaller();
		// 设置编码字符集
		marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
		// 格式化XML输出,有分行和缩进
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		// 打印到控制台
		marshaller.marshal(obj, System.out);
		marshaller.marshal(obj, file);
	}
	
	/**
	 * @Description: XML转换为对象
	 *
	 * @param <T>
	 * @param file
	 * @param beanClass
	 * @return
	 * @throws Exception
	 *
	 * @Title: JAXBUtil.java
	 * @Copyright: Copyright (c) 2014
	 *
	 * @author Comsys-LZP
	 * @date 2014-6-10 下午04:24:50
	 * @version V2.0
	 */
	@SuppressWarnings("unchecked")
	public <T> T xmlStrToObject(File file, Class<T> beanClass) throws Exception {
		T bean = beanClass.newInstance();
		JAXBContext context = JAXBContext.newInstance(beanClass);
		Unmarshaller unmarshaller = context.createUnmarshaller();
		bean = (T) unmarshaller.unmarshal(file);
		return bean;
	}
}

这其实都是Java中的基础,没事的时候都可以看看Java的源码和Jdk API等等,会看到你可能想都没有想过的东西!马上上测试类:
/**
 * @Description: 
 *
 * @Title: JAXBTest.java
 * @Package com.joyce.test
 * @Copyright: Copyright (c) 2014
 *
 * @author Comsys-LZP
 * @date 2014-6-10 下午03:04:05
 * @version V2.0
 */
package com.joyce.test;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.joyce.bean.Student;
import com.joyce.bean.Teacher;
import com.joyce.util.JAXBUtil;

/**
 * @Description: 测试类
 *
 * @ClassName: JAXBTest
 * @Copyright: Copyright (c) 2014
 *
 * @author Comsys-LZP
 * @date 2014-6-10 下午03:04:05
 * @version V2.0
 */
public class JAXBTest {
	public static void main(String[] args) {
		try {
			Teacher teacher = new Teacher("JuanJuan", "女", 22);
			Student student = new Student("Joyce.Luo", "男", 21);
			Student student2 = new Student("Phang.Law", "男", 18);
			JAXBUtil util = new JAXBUtil();
			List<Student> stuList = new ArrayList<Student>();
			stuList.add(student);
			stuList.add(student2);
			teacher.setStudents(stuList);
			String xmlTeaStr = util.objectToXmlStr(teacher, Teacher.class);
			System.out.println("\n包含集合的对象转换为XML:\n" + xmlTeaStr);
			String xmlStr = util.objectToXmlStr(student, Student.class);
			System.out.println("\n对象转换为XML:\n" + xmlStr);
			
			File file = new File("str.xml");
			System.out.println("文件是否存在:" + file.exists());
//			util.objectToXmlStr(student, Student.class, file);
			Student stu = util.xmlStrToObject(file, Student.class);
			System.out.println("\nXML转换为对象:\n" + stu.getName() + "\t" + stu.getSex() + "\t" + stu.getAge());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

结果展示:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Teacher>
    <age>22</age>
    <name>JuanJuan</name>
    <sex>女</sex>
    <Student name="Joyce.Luo">
        <age>21</age>
        <sex>男</sex>
    </Student>
    <Student name="Phang.Law">
        <age>18</age>
        <sex>男</sex>
    </Student>
</Teacher>

包含集合的对象转换为XML:
<?xml version="1.0" encoding="UTF-8"?>
<Teacher>
    <age>22</age>
    <name>JuanJuan</name>
    <sex>女</sex>
    <Student name="Joyce.Luo">
        <age>21</age>
        <sex>男</sex>
    </Student>
    <Student name="Phang.Law">
        <age>18</age>
        <sex>男</sex>
    </Student>
</Teacher>

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Student name="Joyce.Luo">
    <age>21</age>
    <sex>男</sex>
</Student>

对象转换为XML:
<?xml version="1.0" encoding="UTF-8"?>
<Student name="Joyce.Luo">
    <age>21</age>
    <sex>男</sex>
</Student>

文件是否存在:true

XML转换为对象:
Joyce.Luo	男	21

各位有什么好建议,欢迎提哦!完整资源下载地址: http://download.csdn.net/download/luo201227/7505479

JAXB完成XML与Java对象的互转,布布扣,bubuko.com

JAXB完成XML与Java对象的互转

标签:xml   object   jaxb   

原文地址:http://blog.csdn.net/luo201227/article/details/31374849

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!