zoukankan      html  css  js  c++  java
  • XML 处理利器 : XStream

    XStream 概述

         XStream 是一套简洁易用的开发类库,用于将Java对象序列化为XML或者将XML反序列化为JAVA对象,是JAVA对象和XML之间一个双向转换器。

    举例

        采用User用户对象和LoginLog登录日志对象作为XStream实例转换对象. 例子简单,直接贴代码了.
           User.java 
           
    package com.baobaotao.domain;
    
    import java.io.Serializable;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    import java.util.Map;
    
    public class User implements Serializable {
    	private int userId;
    	private String userName;
    	private String password;
    	private int credits;
    	private String lastIp;
    	private Date lastVisit;
    	private List logs; 
    	private Map datas;
    	
    	public List<LoginLog> getLogs() {
    		return logs;
    	}
    	public void setLogs(List logs) {
    		this.logs = logs;
    	}
    	public int getUserId() {
    		return userId;
    	}
    	public void setUserId(int userId) {
    		this.userId = userId;
    	}
    	public String getUserName() {
    		return userName;
    	}
    	public void setUserName(String userName) {
    		this.userName = userName;
    	}
    	public String getPassword() {
    		return password;
    	}
    	public void setPassword(String password) {
    		this.password = password;
    	}
    	public int getCredits() {
    		return credits;
    	}
    	public void setCredits(int credits) {
    		this.credits = credits;
    	}
    	public String getLastIp() {
    		return lastIp;
    	}
    	public void setLastIp(String lastIp) {
    		this.lastIp = lastIp;
    	}
    	public Date getLastVisit() {
    		return lastVisit;
    	}
    	public void setLastVisit(Date lastVisit) {
    		this.lastVisit = lastVisit;
    	}
    	
    	public void addLoginLog(LoginLog log){
    		if(this.logs==null){
    			logs = new ArrayList<LoginLog>();
    		}
    		logs.add(log);
    	}
    	
    	public Map getDatas() {
    		return datas;
    	
    	}
    	public void setDatas(Map datas) {
    		this.datas = datas;
    	}
    	
    }
    

    LoginLog.java

    package com.baobaotao.domain;
    
    import java.io.Serializable;
    import java.util.Date;
    
    public class LoginLog implements Serializable {
    	private int loginLogId;
    	private int userId;
    	private String ip;
    	private Date loginDate;
    	
    	public int getLoginLogId() {
    		return loginLogId;
    	}
    	public void setLoginLogId(int loginLogId) {
    		this.loginLogId = loginLogId;
    	}
    	public int getUserId() {
    		return userId;
    	}
    	public void setUserId(int userId) {
    		this.userId = userId;
    	}
    	public String getIp() {
    		return ip;
    	}
    	public void setIp(String ip) {
    		this.ip = ip;
    	}
    	public Date getLoginDate() {
    		return loginDate;
    	}
    	public void setLoginDate(Date loginDate) {
    		this.loginDate = loginDate;
    	}
    	
    
    }
    

    下面就开始使用XStream进行对象与 XML之间的转换.
    package com.baobaotao.oxm.xtream;
    
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.util.Date;
    
    import com.baobaotao.domain.LoginLog;
    import com.baobaotao.domain.User;
    import com.thoughtworks.xstream.XStream;
    import com.thoughtworks.xstream.io.xml.DomDriver;
    
    public class XStreamSample {
    	
        private static XStream xstream;
        static{
        	//创建XStream实例并指定一个XML	解析器
        	xstream=new XStream(new DomDriver());
        }
        
        //初始化转换对象
        public static User getUser(){
        	LoginLog log1=new LoginLog();
        	log1.setIp("192.168.1.91");
        	log1.setLoginDate(new Date());
        	
        	User user=new User();
        	user.setUserId(1);
        	user.setUserName("xstream");
        	user.addLoginLog(log1);
        	
        	return user;
        }
        
        //Java  对象转换成XML
        public static void objectToXML() throws Exception{
        	
        	//获取转换User对象的实例
        	User user=getUser();
        	//实例化一个文件输出流
        	FileOutputStream fileOutputStream=new FileOutputStream("XStreamSample.xml");
        	
        	//将User对象转换为XML,并保存到指定文件
        	xstream.toXML(user,fileOutputStream);
        }
        
        
        //XML转换为Java对象
        public static User XMLToObject() throws Exception{
        	//实例化一个文件输入流
        	FileInputStream inputStream=new FileInputStream("XStreamSample.xml");
        	//将XML文件输入流转化为对象
        	User user=(User) xstream.fromXML(inputStream);
        	
        	for(LoginLog log :user.getLogs()){
        		if(log!=null){
        			System.out.println("访问IP:"+log.getIp());
        		}
        	}
        }
    
    }
    

    编写测试类
    package com.baobaotao.oxm.xstream;
    
    import static org.junit.Assert.assertEquals;
    import static org.junit.Assert.assertNotNull;
    
    import java.io.BufferedReader;
    import java.io.FileReader;
    
    import org.junit.Test;
    
    import com.baobaotao.domain.LoginLog;
    import com.baobaotao.domain.User;
    import com.baobaotao.oxm.xtream.XStreamSample;
    
    public class TestXStreamSample {
    
    
    	@Test
    	public void objectToXml()throws Exception {
    		XStreamSample.objectToXML();
    		FileReader reader = new FileReader("XStreamSample.xml");
    		BufferedReader br = new BufferedReader(reader);
    		StringBuffer sb = new StringBuffer("");
    		String s;
    		while ((s = br.readLine()) != null) {
    			sb.append(s);
    		}
    		System.out.println(sb.toString());
    		reader.close();
    		br.close();
    //		assertXpathExists("//com.baobaotao.domain.User",sb.toString());
    //		assertXpathExists("//credits",sb.toString());
    //		assertXpathExists("//userName",sb.toString());
    //		assertXpathExists("//com.baobaotao.domain.LoginLog",sb.toString());
    	}
    
    	@Test
    	public void xmlToObject()throws Exception  {
    		XStreamSample.objectToXML();
    		User u = XStreamSample.XMLToObject();
    		assertNotNull(u);
    		assertEquals("xstream", u.getUserName());
    		for (LoginLog log : u.getLogs()) {
    			assertNotNull(log);
    			assertNotNull(log.getIp());
    			assertNotNull(log.getLoginDate());
    		}
    
    	}
    }
    

    生成的XML文件如下:
    <com.baobaotao.domain.User>
      <userId>1</userId>
      <userName>xstream</userName>
      <credits>0</credits>
      <logs>
        <com.baobaotao.domain.LoginLog>
          <loginLogId>0</loginLogId>
          <userId>0</userId>
          <ip>192.168.1.91</ip>
          <loginDate>2015-03-25 07:44:05.783 UTC</loginDate>
        </com.baobaotao.domain.LoginLog>
      </logs>
    </com.baobaotao.domain.User>


    使用XStream 别名

            在默认情况下,Java对象映射到XML的映射,是Java对象属性名对应XML的元素名,Java类的全名对应XML根元素的名字。在实际的应用中,如果XML和Java类都已经存在相应的名字,在进行转换时,需要设置别名进行映射。
            XStream别名配置包含三种情况:
            类别名,用alias(String name ,Class type);
            类成员别名,用aliasField(String alias,Class definedIn,String fieldName);yo
            类成员作为属性别名,用aliasAttribute(Class definedIn,String attributeName,String alias)  ,单独命名没有意义,还要通过useAttributeFor(Class definedIn,String fieldName) 应用到某个类上。


        
    package com.baobaotao.oxm.xtream.alias;
    
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.util.Date;
    
    import com.baobaotao.domain.LoginLog;
    import com.baobaotao.domain.User;
    import com.thoughtworks.xstream.XStream;
    import com.thoughtworks.xstream.io.xml.DomDriver;
    
    /**
     * 别名
     * @author yulei
     */
    public class XStreamAliasSample {
        private static XStream xstream;
          static {
        		xstream=new XStream(new DomDriver());
        		//设置类别名,默认为当前类名称加上包名
        		xstream.alias("loginLog", LoginLog.class);
        		xstream.alias("user", User.class);
        		
        		//设置类成员别名
        		xstream.aliasField("id", User.class, "userId");
        		//把LoginLog的userId属性视为XML属性,默认为XML的元素
        		xstream.aliasAttribute(LoginLog.class, "userId","id");
        		xstream.useAttributeFor(LoginLog.class, "userId");
        		
        		//去掉集合类型生成XML的父节点,即忽略XML中的<logs></logs>标记
        		xstream.addImplicitCollection(User.class,"logs");
        		
          }
          
          
        //初始化转换对象
          public static User getUser(){
          	LoginLog log1=new LoginLog();
          	log1.setIp("192.168.1.91");
          	log1.setLoginDate(new Date());
          	
          	User user=new User();
          	user.setUserId(1);
          	user.setUserName("xstream");
          	user.addLoginLog(log1);
          	
          	return user;
          }
          
          //Java  对象转换成XML
          public static void objectToXML() throws Exception{
          	
          	//获取转换User对象的实例
          	User user=getUser();
          	//实例化一个文件输出流
          	FileOutputStream fileOutputStream=new FileOutputStream("XStreamSample.xml");
          	
          	//将User对象转换为XML,并保存到指定文件
          	xstream.toXML(user,fileOutputStream);
          }
          
          //XML转换为Java对象
          public static User XMLToObject() throws Exception{
          	//实例化一个文件输入流
          	FileInputStream inputStream=new FileInputStream("XStreamSample.xml");
          	//将XML文件输入流转化为对象
          	User user=(User) xstream.fromXML(inputStream);
          	
          	for(LoginLog log :user.getLogs()){
          		if(log!=null){
          			System.out.println("访问IP:"+log.getIp());
          		}
          	}
      		return user;
          }
    
    }
    






  • 相关阅读:
    zip 中文文件夹为空问题
    webview长按文本区域不显示文字放大镜等方法
    crash
    精疲力尽先生的造访
    告别忙碌的2017,迎来更加忙碌的2018
    传说中的59分!!
    为什么我一定吵不过女人?
    人挪活!
    低谷时,请读书!
    java小入门的感觉
  • 原文地址:https://www.cnblogs.com/wuyida/p/6300345.html
Copyright © 2011-2022 走看看