小编给大家分享一下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输出更简洁,可以为您的自定义类名创建别名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互转工具类有哪些”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。