java xtream bean xml

import java.util.Iterator;
import java.util.Map;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.io.xml.XmlFriendlyReplacer;
import com.thoughtworks.xstream.io.xml.XppDriver;
@SuppressWarnings("deprecation")
public class XMLBeanUtils {


/**
* 将Bean转换为XML
*
* @param clazzMap
* 别名-类名映射Map
* @param bean
* 要转换为xml的bean对象
* @return XML字符串
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static String bean2xml(Map<String, Class> clazzMap, Object bean) {
XStream xstream = new XStream(new XppDriver(new XmlFriendlyReplacer("_-", "_")));
for (Iterator it = clazzMap.entrySet().iterator(); it.hasNext();) {
Map.Entry<String, Class> m = (Map.Entry<String, Class>) it.next();
xstream.alias(m.getKey(), m.getValue());
}
String xml = xstream.toXML(bean);
return xml;
}

/**
* 将XML转换为Bean
*
* @param clazzMap
* 别名-类名映射Map
* @param xml
* 要转换为bean对象的xml字符串
* @return Java Bean对象
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Object xml2Bean(Map<String, Class> clazzMap, String xml) {
XStream xstream = new XStream(new DomDriver());
for (Iterator it = clazzMap.entrySet().iterator(); it.hasNext();) {
Map.Entry<String, Class> m = (Map.Entry<String, Class>) it.next();
xstream.alias(m.getKey(), m.getValue());
}
Object bean = xstream.fromXML(xml);
return bean;
}

/**
* 获取XStream对象 `
*
* @param clazzMap
* 别名-类名映射Map
* @return XStream对象
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static XStream getXStreamObject(Map<String, Class> clazzMap) {
XStream xstream = new XStream(new DomDriver());
for (Iterator it = clazzMap.entrySet().iterator(); it.hasNext();) {
Map.Entry<String, Class> m = (Map.Entry<String, Class>) it.next();
xstream.alias(m.getKey(), m.getValue());
}
return xstream;
}


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值