XStream xml与javabean之间的互转

前端之家收集整理的这篇文章主要介绍了XStream xml与javabean之间的互转前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

XStream是thoughtworks公司发布的一个简单的Java类库,用于将JavaBean序列化为XML,并且能够将XML文件反向转换为JavaBean.

实例:

user.java

[java] view plain copy
  1. importjava.io.Serializable;
  2. publicclassUserimplementsSerializable{
  3. privateStringid;
  4. privateStringname;
  5. privateStringage;
  6. publicUser(){
  7. }
  8. publicUser(Stringid,Stringname,Stringage){
  9. this.id=id;
  10. this.name=name;
  11. this.age=age;
  12. }
  13. publicStringgetId(){
  14. returnid;
  15. voidsetId(Stringid){
  16. publicStringgetName(){
  17. returnname;
  18. voidsetName(Stringname){
  19. this.name=name;
  20. publicStringgetAge(){
  21. returnage;
  22. voidsetAge(Stringage){
  23. }


BaseBean.java

copy
    importjava.util.ArrayList;
  1. importjava.util.List;
  2. classBaseBean{
  3. privateList<User>userList;
  4. publicBaseBean(){
  5. userList=newArrayList<User>();
  6. publicList<User>getUserList(){
  7. returnuserList;
  8. voidsetUserList(List<User>userList){
  9. this.userList=userList;
  10. voidaddUser(Useruser){
  11. userList.add(user);

  12. xstream代码

    copy
    classXStreamTest{
  1. staticvoidmain(String[]args){
  2. //javabean转xml
  3. List<User>users=newArrayList<User>();
  4. users.add(newUser("123","爱边程","23"));
  5. users.add(newUser("456","刘大拿","24"));
  6. BaseBeanbase=newBaseBean();
  7. base.setUserList(users);
  8. XStreamxs=newXStream();
  9. xs.alias("root",BaseBean.class);
  10. xs.alias("user",User.class);
  11. xs.aliasField("list",153); font-weight:bold; background-color:inherit">class,"userList");
  12. Stringxml=xs.toXML(base);
  13. System.out.println("javabean转成xml为:\n"+xml);
  14. //xml转javabean
  15. XStreamxs1=newXStream(newDomDriver());
  16. xs1.alias("root",153); font-weight:bold; background-color:inherit">class);//注意此处要把原要转换的bean类定义别名为根节点的名字,如上面的xml的根节点为<root>
  17. xs1.alias("user",153); font-weight:bold; background-color:inherit">class); //此处与上面相同
  18. xs1.aliasField("list",108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> base=(BaseBean)xs1.fromXML(xml);
  19. users=base.getUserList();
  20. System.out.println("xml转成javabean为:");
  21. for(Useru:users){
  22. System.out.println("id="+u.getId()+",name="+u.getName()+",age="+u.getAge());
  23. }
原文链接:/xml/295359.html

猜你在找的XML相关文章