溫馨提示×

溫馨提示×

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

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

JavaBean和XML互轉工具類有哪些

發(fā)布時間:2021-01-21 14:29:47 來源:億速云 閱讀:212 作者:小新 欄目:編程語言

小編給大家分享一下JavaBean和XML互轉工具類有哪些,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

使用XStream的jar包
x-stream.github.io/index.html
jar包見附件
XStream is a simple library to serialize objects to XML and back again.
實體類

public class Person {
	 
	 private String firstname;
	 private String lastname;
	 private PhoneNumber phone;
	 private PhoneNumber fax;
	 
	 public Person(String firstname,String lastname){
		 this.firstname = firstname; 
		 this.lastname = lastname; 
	 }
	
	 public String getFirstname() {
		return firstname;
	}
	public void setFirstname(String firstname) {
		this.firstname = firstname;
	}
	public String getLastname() {
		return lastname;
	}
	public void setLastname(String lastname) {
		this.lastname = lastname;
	}
	public PhoneNumber getPhone() {
		return phone;
	}
	public void setPhone(PhoneNumber phone) {
		this.phone = phone;
	}
	public PhoneNumber getFax() {
		return fax;
	}
	public void setFax(PhoneNumber fax) {
		this.fax = fax;
	}
	 
	
}

public class PhoneNumber {
	private int code;
	private String number;
	
	public PhoneNumber(int code,String number){
		this.code = code;
		this.number = number;
	}
	
	public int getCode() {
		return code;
	}
	public void setCode(int code) {
		this.code = code;
	}
	public String getNumber() {
		return number;
	}
	public void setNumber(String number) {
		this.number = number;
	}
}

工具類

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.StaxDriver;
import com.wind.study.entity.Person;
import com.wind.study.entity.PhoneNumber;

/**
 * 
* @author wind
* @date 2016年9月13日 下午4:49:32 
* @Description: bean/XML 互轉
 */
public class BeanXMLConvertUtil {
	
	public static void main(String[] args) {
		XStream xstream = new XStream(new StaxDriver());
		
		//XStream的XML輸出更簡潔,可以為您的自定義類名創(chuàng)建別名XML元素名稱。這是唯一類型的映射需要使用XStream甚至是可選的。
		xstream.alias("person", Person.class);
		xstream.alias("phonenumber", PhoneNumber.class);
		
		Person joe = new Person("Joe", "Walnes");
		joe.setPhone(new PhoneNumber(123, "1234-456"));
		joe.setFax(new PhoneNumber(123, "9999-999"));
		
		//bean to XML
		String xml = xstream.toXML(joe);
		//XML to bean
		Person newJoe = (Person)xstream.fromXML(xml);
		
		System.out.println(newJoe.getFirstname());
		
		System.out.println(xml);
	}
}

以上是“JavaBean和XML互轉工具類有哪些”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

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

AI