前端之家收集整理的这篇文章主要介绍了
利用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;
- }