我是靠谱客的博主 踏实溪流,这篇文章主要介绍详细介绍JavaBean和XML互转工具类,现在分享给大家,希望可以做个参考。

使用XStream的jar包
x-stream.github.io/index.html
jar包见附件
XStream is a simple library to serialize objects to XML and back again.
实体类

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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; } }
登录后复制

工具类

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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互转工具类的详细内容,更多请关注靠谱客其它相关文章!

最后

以上就是踏实溪流最近收集整理的关于详细介绍JavaBean和XML互转工具类的全部内容,更多相关详细介绍JavaBean和XML互转工具类内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(103)

评论列表共有 0 条评论

立即
投稿
返回
顶部