详细介绍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 XMLString xml = xstream.toXML(joe);//XML to beanPerson newJoe = (Person)xstream.fromXML(xml);System.out.println(newJoe.getFirstname());System.out.println(xml);}}

登录后复制

以上就是详细介绍JavaBean和XML互转工具类的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2418185.html

(0)
上一篇 2025年3月3日 02:13:05
下一篇 2025年2月23日 12:17:37

AD推荐 黄金广告位招租... 更多推荐

发表回复

登录后才能评论