JavaBean與xml檔案的互轉——xstream
阿新 • • 發佈:2018-12-10
目錄
一.所需jar包
- 1.1.xstream.jar——互轉的基礎jar包
- 1.2.xmlpull.jar——JavaBean轉成xml檔案需要的jar包
- 1.3.xpp3-1.1.4c.jar——xml轉成JavaBean物件所需要的jar包
二.JavaBean物件與xml互轉之準備相關實體類
package bean; import java.util.List; /** * This is the Customer class * * @author: lvxiaobu * @createDate: 2018-09-18 14:45 */ public class Customer { private String commodity; public String getCommodity() { return commodity; } public void setCommodity(String commodity) { this.commodity = commodity; } }
package bean; import java.util.List; /** * This is the User class * * @author: lvxiaobu * @createDate: 2018-09-18 14:44 */ public class User { private String name; private String age; private List<Customer> customer; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public List<Customer> getCustomer() { return customer; } public void setCustomer(List<Customer> customer) { this.customer = customer; } }
三.JavaBean物件轉成xml
public static void main(String[] args) { User user = new User(); Customer customer1 = new Customer(); Customer customer2 = new Customer(); customer1.setCommodity("手錶"); customer2.setCommodity("電腦"); List<Customer> list = new ArrayList<Customer>(); list.add(customer1); list.add(customer2); user.setName("呂小布"); user.setAge("23"); user.setCustomer(list); //建立xStream物件 XStream xStream = new XStream(); //給class起別名(建議先註釋掉,看一下不起別名輸出的xml格式) xStream.alias("User",User.class); xStream.alias("Customer",Customer.class); //呼叫toXML 將物件轉成字串 String s = xStream.toXML(user); System.out.println(s); //將字串寫入檔案 //handIo(s); }
控制檯輸出顯示:
<User>
<name>呂小布</name>
<age>23</age>
<customer>
<Customer>
<commodity>手錶</commodity>
</Customer>
<Customer>
<commodity>電腦</commodity>
</Customer>
</customer>
</User>
四.xml檔案轉JavaBean物件
public static void main(String[] args) {
//模擬一個xml格式字串
String xml = "<user>\n" +
" <name>beyondLi</name>\n" +
" <age>23</age>\n" +
" <customer>\n" +
" <Customer>\n" +
" <commodity>商品1</commodity>\n" +
" </Customer>\n" +
" <Customer>\n" +
" <commodity>商品2</commodity>\n" +
" </Customer>\n" +
" </customer>\n" +
"</user>";
XStream xstream = new XStream();
//不設定會報錯
XStream.setupDefaultSecurity(xstream);
xstream.allowTypes(new Class[]{User.class, Customer.class});
//將別名與xml名字相對應
xstream.alias("User", User.class);
xstream.alias("Customer", Customer.class);
User user2 = (User) xstream.fromXML(xml.toString());
System.out.println(user2);
}
控制檯輸出:
[email protected]
正常流程中,應該是給將JavaBean物件轉成xml檔案,或者是讀取指定xml檔案然後將其內容轉成JavaBean物件。這個時候就需要新增IO流來操作檔案了。
IO流的資源網路上一大堆,在這裡我放一個我自己整理的IO流的案例<該IO流案例和此篇部落格其實一個demo中的例子>,
如果有書寫錯誤的地方,或者是有問題的地方請及時評論或者是私信我,以免誤導個別萌新。
雖然我也是個萌新。
你好,我叫呂小布。