XStream使用注解的方式格式化生成的xml

前端之家收集整理的这篇文章主要介绍了XStream使用注解的方式格式化生成的xml前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

实体类:

package cn.framework.t2;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import com.thoughtworks.xstream.annotations.XStreamConverter;
import com.thoughtworks.xstream.annotations.XStreamImplicit;

@XStreamAlias("user")
public class User {
	@XStreamAsAttribute
	@XStreamAlias("id")
	private int userId;
	
	@XStreamAlias("userName")
	private String userName;
	
	@XStreamAlias("pwd")
	private String pwd;
	
//	@XStreamImplicit
	private List<UserLog> logs=new ArrayList<UserLog>();
	
	@XStreamConverter(DateConverter1.class)
	private Date lastVisted;
	
	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 getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	public List getLogs() {
		return logs;
	}
	public void setLogs(List logs) {
		this.logs = logs;
	}
	public Date getLastVisted() {
		return lastVisted;
	}
	public void setLastVisted(Date lastVisted) {
		this.lastVisted = lastVisted;
	}
	@Override
	public String toString() {
		return "User [userId=" + userId + ",userName=" + userName + ",pwd="
				+ pwd + ",logs=" + logs + ",lastVisted=" + lastVisted + "]";
	}
	
	
}

package cn.framework.t2;

import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;

@XStreamAlias("log")
public class UserLog {
	@XStreamAsAttribute
	@XStreamAlias("id")
	private int logId;
	
	@XStreamAlias("ip")
	private String ip;
	
	public int getLogId() {
		return logId;
	}
	public void setLogId(int logId) {
		this.logId = logId;
	}
	public String getIp() {
		return ip;
	}
	public void setIp(String ip) {
		this.ip = ip;
	}
	@Override
	public String toString() {
		return "UserLog [logId=" + logId + ",ip=" + ip + "]";
	}
	
	
}


常用注解:

@XStreamAlias 别名注解;

@XStreamAsAttribute 转换成属性,而不是子标签

@XStreamOmitField 忽略字段

@XStreamConverter 注入转换器(转换器要求无参构造器)

@XStreamImplicit 忽略集合名称标签



转换器
package cn.framework.t2;

import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;

import com.thoughtworks.xstream.converters.ConversionException;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

public class DateConverter1 implements Converter{
	private Locale locale;
	
	public DateConverter1(){
		super();
		this.locale=locale.SIMPLIFIED_CHINESE;
	}
	
	//判断需要转换的类型
	@Override
	public boolean canConvert(Class clazz) {
		// TODO Auto-generated method stub
		return Date.class.isAssignableFrom(clazz);
	}

	//编写java对象到xml的逻辑
	@Override
	public void marshal(Object value,HierarchicalStreamWriter writer,MarshallingContext context) {
		DateFormat formatter = DateFormat.getDateInstance(DateFormat.FULL,this.locale);
		writer.setValue(formatter.format(value));
	}

	//编写xml到java对象的逻辑
	@Override
	public Object unmarshal(HierarchicalStreamReader reader,UnmarshallingContext context) {
		GregorianCalendar calendar = new GregorianCalendar();
		DateFormat formatter = DateFormat.getDateInstance(DateFormat.FULL,this.locale);
		try{
			calendar.setGregorianChange(formatter.parse(reader.getValue()));
		}catch(ParseException e){
			throw new ConversionException(e.getMessage(),e);
		}
		return calendar.getGregorianChange();
	}

}

注意:与上一篇的转换器不同,这里构造器使用的是无参数的方式。


package cn.framework.t2;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Locale;

import org.apache.log4j.Logger;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class XStreamUtils1 {
	private static final Logger logger=Logger.getLogger("cn.framework.t1.XStreamUtils1");
	
	private static XStream xstream;
	static{
		logger.info("init xstream ...");
		xstream=new XStream(new DomDriver());
		
		//加载指定有XStream注解的bean
//		xstream.processAnnotations(User.class);
		
		//自动加载所有XStream注解的bean,与上面的区别是上面加载指定的bean
		xstream.autodetectAnnotations(true);
	}
	
	public static void objectToXML(User user) throws FileNotFoundException{
		logger.info("do objectToXML ...");
		FileOutputStream fileOutputStream = new FileOutputStream("e:/out/xstream_user.xml");
		xstream.toXML(user,fileOutputStream);
	}
	
	public static void xmlToObject() throws FileNotFoundException{
		logger.info("do xmlToObject ...");
		FileInputStream input = new FileInputStream("e:/out/xstream_user.xml");
		User user=(User) xstream.fromXML(input);
		System.out.println(user);
	}
	
	
}

测试:
package cn.framework.t2;

import java.io.FileNotFoundException;
import java.text.ParseException;
import java.util.Date;

public class Test1 {

	public static void main(String[] args) throws FileNotFoundException,ParseException {
		User user = new User();
		user.setLastVisted(new Date());
		user.setPwd("123456");
		user.setUserId(1);
		user.setUserName("aaa");
		
		
		UserLog userLog = new UserLog();
		userLog.setIp("127.0.0.1");
		userLog.setLogId(1);
		user.getLogs().add(userLog);
		
		UserLog userLog1 = new UserLog();
		userLog1.setIp("127.0.0.1");
		userLog1.setLogId(2);
		user.getLogs().add(userLog1);
		
		XStreamUtils1.objectToXML(user);
		
//		XStreamUtils1.xmlToObject();
		
	}

}
原文链接:https://www.f2er.com/xml/293585.html

猜你在找的XML相关文章