溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Jaxb2實現(xiàn)Bean與xml互轉(zhuǎn)的案例分析

發(fā)布時間:2020-10-24 15:43:09 來源:億速云 閱讀:298 作者:小新 欄目:編程語言

小編給大家分享一下Jaxb2實現(xiàn)Bean與xml互轉(zhuǎn)的案例分析,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!

一、重要類說明

JAXBContext類,是應(yīng)用的入口,用于管理XML/Java綁定信息。

Marshaller接口,將Java對轉(zhuǎn)化為XML數(shù)據(jù)。

Unmarshaller接口,將XML轉(zhuǎn)化為Java對象。

@XmlType,將Java類或枚舉類型映射到XML模式類型

@XmlAccessorType(XmlAccessType.FIELD) ,控制字段或?qū)傩缘男蛄谢?。FIELD表示JAXB將自動綁定Java類中的每個非靜態(tài)的(static)、

非瞬態(tài)的(由@XmlTransient標(biāo) 注)字段到XML。其他值還有XmlAccessType.PROPERTY和XmlAccessType.NONE。

@XmlAccessorOrder,控制JAXB 綁定類中屬性和字段的排序。

@XmlJavaTypeAdapter,使用定制的適配器(即擴展抽象類XmlAdapter并覆蓋marshal()和unmarshal()方法),以序列化Java類為XML。

@XmlElementWrapper ,對于數(shù)組或集合(即包含多個元素的成員變量),生成一個包裝該數(shù)組或集合的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、轉(zhuǎn)化工具類

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轉(zhuǎn)XML*/
	public static String beanToXml(Object obj) {
		String result = null;
		try {
			JAXBContext context = JAXBContext.newInstance(obj.getClass());
			Marshaller marshaller = context.createMarshaller();
			//決定是否在轉(zhuǎn)換成xml時同時進行格式化(即按標(biāo)簽自動換行,否則即是一行的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、測試結(jié)果

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實現(xiàn)Bean與xml互轉(zhuǎn)的案例分析有了一定的了解,想了解更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI