加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 23:46:38 所属栏目:百科 来源:网络整理
导读: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);} catc
	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;
	}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读