旗下导航:搜·么
当前位置:网站首页 > XML教程 > 正文

Jaxb2完成Bean与xml互转的示例代码详解【XML教程】,Jaxb2,Bean,xml

作者:搜教程发布时间:2019-12-01分类:XML教程浏览:90评论:0


导读:一、主要类申明JAXBContext类,是运用的进口,用于治理XML/Java绑定信息。Marshaller接口,将Java对转化为XML数据。Unmarshall...
一、主要类申明

JAXBContext类,是运用的进口,用于治理XML/Java绑定信息。

Marshaller接口,将Java对转化为XML数据。

Unmarshaller接口,将XML转化为Java对象。

@XmlType,将Java类或罗列范例映射到XML形式范例

@XmlAccessorType(XmlAccessType.FIELD) ,掌握字段或属性的序列化。FIELD示意JAXB将自动绑定Java类中的每一个非静态的(static)、

非瞬态的(由@XmlTransient标 注)字段到XML。其他值另有XmlAccessType.PROPERTY和XmlAccessType.NONE。

@XmlAccessorOrder,掌握JAXB 绑定类中属性和字段的排序。

@XmlJavaTypeAdapter,运用定制的适配器(即扩大抽象类XmlAdapter并掩盖marshal()和unmarshal()要领),以序列化Java类为XML。

@XmlElementWrapper ,关于数组或鸠合(即包括多个元素的成员变量),生成一个包装该数组或鸠合的XML元素(称为包装器)。

@XmlRootElement,将Java类或罗列范例映射到XML元素。

@XmlElement,将Java类的一个属性映射到与属性同名的一个XML元素。

@XmlAttribute,将Java类的一个属性映射到与属性同名的一个XML属性。

二、实例

1、JavaBean

import java.util.Date;
import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

import com.tzz.util.xml.JaxbDateSerializer;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "country")
@XmlType(propOrder = { "id", "createDate", "name", "provinceList" })
public class Country {

	private Integer id;
	@XmlJavaTypeAdapter(JaxbDateSerializer.class)
	private Date createDate;
	@XmlElement(name = "name")
	private String name;
	@XmlElementWrapper(name = "provinces")
	@XmlElement(name = "province")
	private List<Province> provinceList;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public Date getCreateDate() {
		return createDate;
	}

	public void setCreateDate(Date createDate) {
		this.createDate = createDate;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public List<Province> getProvinceList() {
		return provinceList;
	}

	public void setProvinceList(List<Province> provinceList) {
		this.provinceList = provinceList;
	}
}
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(propOrder = { "name", "provCity" })
public class Province {

	@XmlElement(name = "name")
	private String name;
	@XmlElement(name = "provCity")
	private String provCity;

	public String getProvCity() {
		return provCity;
	}

	public void setProvCity(String provCity) {
		this.provCity = provCity;
	}

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}

2、转化东西类

import java.io.StringReader;
import java.io.StringWriter;

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

/**
 * Jaxb 2.0
 *
 */
public class JaxbXmlUtil {

	@SuppressWarnings("unchecked")
	public static <T> T xmlToBean(String xml, Class<T> beanClass) {
		try {
			JAXBContext jaxbContext = JAXBContext.newInstance(beanClass);
			Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
			T user = (T) unmarshaller.unmarshal(new StringReader(xml));
			return user;
		} catch (JAXBException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**Bean转XML*/
	public static String beanToXml(Object obj) {
		String result = null;
		try {
			JAXBContext context = JAXBContext.newInstance(obj.getClass());
			Marshaller marshaller = context.createMarshaller();
			//决议是不是在转换成xml时同时举行格式化(即按标签自动换行,不然等于一行的xml)
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			//Marshaller.JAXB_ENCODING xml的编码体式格局
			marshaller.setProperty(Marshaller.JAXB_ENCODING, "utf-8");
			StringWriter writer = new StringWriter();
			marshaller.marshal(obj, writer);
			result = writer.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}

3、测试类

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.junit.Test;

import com.tzz.test.util.xml.entity.Country;
import com.tzz.test.util.xml.entity.Province;
import com.tzz.util.xml.JaxbXmlUtil;

public class TestJaxbBeanToXmlUtil {

	@Test
	public void testBeanToXml() {
		Country country = new Country();
		country.setId(1);
		country.setCreateDate(new Date());
		country.setName("中国");
		
		List<Province> list = new ArrayList<Province>();
		Province province = new Province();
		province.setName("广东省");
		province.setProvCity("广州市");
		Province province2 = new Province();
		province2.setName("湖南省");
		province2.setProvCity("长沙市");
		list.add(province);
		list.add(province2);
		country.setProvinceList(list);

		String xml = JaxbXmlUtil.beanToXml(country);
		System.out.println(xml);
	}

	@Test
	public void testXmlToBean() {
		String xml = "<?xml version='1.0' encoding='utf-8' ?>" 
				+ "<country>" 
				+ "<id>1</id>"
				+ "<createDate>2016-03-10 09:36:01</createDate>" 
				+ "<name>中国</name>" 
				+ "<provinces>" 
				+ "<province><name>广东省</name><provCity>广州市</provCity></province>" 
				+ "<province><name>湖南省</name><provCity>长沙市</provCity></province>" 
				+ "</provinces>" 
				+ "</country>";
		Country country = JaxbXmlUtil.xmlToBean(xml, Country.class);
		System.out.println(country.getId() + "--" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
				.format(country.getCreateDate()) + "--" + country.getName());
		for (Province p : country.getProvinceList()) {
			System.out.println(p.getName() + "---" + p.getProvCity());
		}
	}
}

4、测试效果

4.1、运转testBeanToXml要领

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<country>
    <id>1</id>
    <createDate>2016-03-10 05:24:57</createDate>
    <name>中国</name>
    <provinces>
        <province>
            <name>广东省</name>
            <provCity>广州市</provCity>
        </province>
        <province>
            <name>湖南省</name>
            <provCity>长沙市</provCity>
        </province>
    </provinces>
</country>

4.2、运转testXmlToBean要领

1--2016-03-10 09:36:01--中国
广东省---广州市
湖南省---长沙市

以上就是Jaxb2完成Bean与xml互转的示例代码详解的细致内容,更多请关注ki4网别的相干文章!

标签:Jaxb2Beanxml


欢迎 发表评论: