XML和Java Bean互相转换是一个很有用的功能,因为两者有着前后合作的关系,但解析的过程比较痛苦。下面介绍如何进行XML和Java Bean的互相转换。
最近项目中用到了xml和java bean的转换
用到xml的时候我们需要遍历解析。。。然后将解析的值放入声明好的java bean,过程很痛苦,结果很美好
我们能不能直接从xml转化到java bean呢,或者直接成java bean转化到xml呢?
答案是OK的
使用jar包:org.nuxeo.common.xmap
写个小例子
XML
1.< ?xml version="1.0" encoding="UTF-8"?>
2.< books>
3.< book no="1">
4.< title>java是傻逼< /title>
5.< subject>java< /subject>
6.< subject>xml< /subject>
7.< price>10< /price>
8.< /book>
9.< book no="2">
10.< title>c++程序设计< /title>
11.< subject>C++< /subject>
12.< subject>c< /subject>
13.< price>10< /price>
14.< /book>
15.< /books>
Books类
16.import java.util.ArrayList;
17.import java.util.List;
18.
19.import org.nuxeo.common.xmap.annotation.XNodeList;
20.import org.nuxeo.common.xmap.annotation.XObject;
21.
22.@XObject(value = "books")
23.public class Books {
24. @XNodeList(value = "book", type = ArrayList.class, componentType = Book.class)
25. private List< Book> book;
26.
27. public List< Book> getBook() {
28. return book;
29. }
30.
31. public void setBook(List< Book> book) {
32. this.book = book;
33. }
34.
35. public void addBook(Book b){
36. if(book==null){
37. book=new ArrayList< Book>();
38. }
39. book.add(b);
40. }
41.}
42.
Book类
43.import java.util.ArrayList;
44.import java.util.List;
45.
46.import org.nuxeo.common.xmap.annotation.XNode;
47.import org.nuxeo.common.xmap.annotation.XNodeList;
48.import org.nuxeo.common.xmap.annotation.XObject;
49.
50.
52.public class Book {
53. @XNode("title")
54. private String title;
55.
56. @XNode("@no")
57. private String no;
58.
59. @XNodeList(value = "subject", type = ArrayList.class, componentType = String.class)
60. private List< String> subjects;
61.
62. @XNode("price")
63. private int price;
64.
65. public String getTitle() {
66. return title;
67. }
68.