设为首页 收藏本站
查看: 334|回复: 0

[经验分享] Apache的xstream解析XML工具类

[复制链接]

尚未签到

发表于 2017-1-8 09:04:56 | 显示全部楼层 |阅读模式
  更新日期20151012

package hrhx.dhm.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Component;
import com.thoughtworks.xstream.XStream;
/**
* @version 20150902
* @author duhongming
*
*/
@Component
public class XmlUtil {
private static XmlUtil instance = null;
private XStream xs = null;
private XmlUtil() {
this.xs = new XStream();
}
/**
* 初始化XmlUtil
* @return
*/
public static synchronized XmlUtil getInstance() {
if (instance == null) {
System.out.println("正在初始化XML处理对象.............");
instance = new XmlUtil();
}
return instance;
}
/**
* 将Object转化为XML字符串
* @param obj
* @return
* @throws Exception
*/
public String toXML(Object obj) throws Exception {
if (obj == null)
return null;
return this.xs.toXML(obj);
}
/**
* 对toXML方法重载,修改<节点名称>
* @param obj
* @param aliasMap
* @return
* @throws Exception
*/
@SuppressWarnings("rawtypes")
public String toXML(Object obj,Map<String,Class> aliasMap) throws Exception {
if (obj == null)
return null;
for(Map.Entry<String, Class> entry:aliasMap.entrySet()){   
this.xs.alias(entry.getKey(), entry.getValue());
}   
return this.xs.toXML(obj);
}
/**
* 将Object转化为XML文件
* @param obj
* @param strFile
* @throws Exception
*/
public void toXMLFile(Object obj, String strFile) throws Exception {
if (obj == null)
return;
if ((strFile == null) || (strFile.equals("")))
throw new Exception("XML保存的文件名不能为空!");
String str = strFile;
str = str.replaceAll("//", "/");
File f = new File(str.substring(  0, str.lastIndexOf("/")));
if (!f.exists())
f.mkdirs();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File(str));
this.xs.toXML(obj, fos);
fos.close();
} catch (Exception e) {
if (fos != null)
fos.close();
e.printStackTrace();
throw new Exception("将对象写到文件" + str + "失败!" + e.getMessage());
}
}
/**
* 将XML字符串转成Object
* @param xml
* @return
* @throws Exception
*/
public Object fromXML(String xml) throws Exception {
if ((xml == null) || (xml.equals("")))
return null;
return this.xs.fromXML(xml);
}
/**
* 将XML文件转成Object
* @param strFile
* @return
* @throws Exception
*/
public Object fromXMLFile(String strFile) throws Exception {
if ((strFile == null) || (strFile.equals("")))
return null;
FileInputStream fis = null;
Object obj = null;
String str = strFile;
str = str.replaceAll("//", "/");
File f = new File(str);
if (!f.exists())
return null;
try {
fis = new FileInputStream(f);
obj = this.xs.fromXML(fis).toString();
fis.close();
} catch (Exception e) {
if (fis != null)
fis.close();
e.printStackTrace();
throw new Exception("从文件" + str + "读取内容进行对象转换时失败!" + e.getMessage());
}
return obj;
}
public static void main(String[] args) throws Exception {
String begin = "2002-10-21 23:12:34";
begin = begin.substring(  5,   7) + "月" + begin.substring(  8,  10) + "日";
List<String> list = new ArrayList<String>();
list.add("duhongming");
list.add("24");
list.add(begin);
String listXml = getInstance().toXML(list);
System.out.println("将List数据转成XML:"+listXml);
System.out.println("将XML数据转成List:"+getInstance().fromXML(listXml));
String templateFileName = System.getProperty("user.dir")+"/target/demo.xml";
getInstance().toXMLFile(list, templateFileName);
System.out.println("将XML文件数据转成List:"+getInstance().fromXMLFile(templateFileName));
Map<String,String> map = new HashMap<String,String>();
map.put("name", "duhongming");
map.put("age", "24");
map.put("birthday", "7月26日");
String mapXml = getInstance().toXML(map);
System.out.println("将Map数据转成XML:"+mapXml);
System.out.println(("将XML数据转成Map:"+getInstance().fromXML(mapXml)));
}
}附Java平台自带的注解功能:
package com.hrhx.db;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlRootElement;
import com.sun.xml.internal.txw2.annotation.XmlElement;
@XmlRootElement
public class TestMenu {
private String menuName;
private String menuUrl;
private String userName;
private String timestamp;
@XmlElement
public String getMenuName() {
return menuName;
}
public void setMenuName(String menuName) {
this.menuName = menuName;
}
@XmlElement
public String getMenuUrl() {
return menuUrl;
}
public void setMenuUrl(String menuUrl) {
this.menuUrl = menuUrl;
}
@XmlElement
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@XmlElement
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public static void main(String[] args) {
JAXBContext jc;
try {
jc = JAXBContext.newInstance(TestMenu.class);
Marshaller ms = jc.createMarshaller();
TestMenu t = new TestMenu();
t.setMenuName("baidu");
t.setMenuUrl("http://www.baidu.com");
t.setTimestamp("2015-10-1");
t.setUserName("zhangsan");
// System.out.println(t);
ms.marshal(t, System.out);
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}




版权声明:本文为博主原创文章,未经博主允许不得转载。

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-325352-1-1.html 上篇帖子: Apache Spark 1.5.0正式发布 下篇帖子: Apache Pig中如何使用Replace函数
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表