zoukankan      html  css  js  c++  java
  • JAXB完毕XML与Java对象的互转

    这段时间都老忙了,甚至连周末全部人员都在赶产品的进度,想想连续上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("
    包括集合的对象转换为XML:
    " + xmlTeaStr);
    			String xmlStr = util.objectToXmlStr(student, Student.class);
    			System.out.println("
    对象转换为XML:
    " + 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("
    XML转换为对象:
    " + stu.getName() + "	" + stu.getSex() + "	" + 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

  • 相关阅读:
    Android MediaPlayer
    MediaPlayer基本使用方式
    css 透明度 一句话搞定透明背景!
    CSS ZOOM 作用[IE6下清除浮动]
    document.execcommand方法
    让position:fixed在IE6下可用
    CSS文档流与块级元素(block)内联元素(inline)那点事
    Android屏幕分辨率详解(VGA、HVGA、QVGA、WVGA、WQVGA)
    重载的乐趣
    线程间调用不同线程创建的控件
  • 原文地址:https://www.cnblogs.com/lcchuguo/p/5353750.html
Copyright © 2011-2022 走看看