利用XStream实现实体对象和xml文件相互转换

	public void Bean2XML(T entity,String file) {
		XStream xstream = new XStream(new DomDriver("utf-8"));
		xstream.alias("root", entity.getClass());//设置root为根节点
		try {
			OutputStream out = new FileOutputStream(file);
			xstream.toXML(entity, out);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
	public T XML2Bean(Class<T> clazz,String file) {
		XStream stream = new XStream(new DomDriver("utf-8"));// xml文件使用utf-8格式
		T entity;
		try {
			InputStream input = new FileInputStream(file);
			stream.alias("root", clazz);
			entity = (T) stream.fromXML(input); // 从配置文件中读取配置,并自动转换为对应的对象
		} catch (FileNotFoundException e1) {
			entity=null;
		}
		return entity;
	}


你可能感兴趣的:(利用XStream实现实体对象和xml文件相互转换)