XStream是一个Java对象和XML相互转换的工具,很好很强大。提供了所有的基础类型、数组、集合等类型直接转换的支持。因此XML常用于数据交换、对象序列化(这种序列化和Java对象的序列化技术有着本质的区别)。
XStream对象相当Java对象和XML之间的转换器,转换过程是双向的。创建XSteam对象的方式很简单,只需要new XStream()即可。
Java到xml,用toXML()方法。
Xml到Java,用fromXML()方法。
public static List getDataList() {
XStream xstream = new XStream(new DomDriver("UTF-8"));
xstream.alias("dataList", ArrayList.class);//别名设置
xstream.alias("data", BusinessDefine.class);
try
{
java.net.URL dir = BusinessDefine.class.getResource("");
//文件地址
final File curDir = new File(java.net.URI.create(dir.toString() + XML_PATH));//XML_PATH为文件名称+后缀
return autoCast(xstream.fromXML(new FileInputStream(curDir)));//xml转java
}
catch (FileNotFoundException e)
{
return null;
}
}
public class DictEvalUtil {
private static final String fileName = "dictEvalConfig.xml";
private static Map<String, BidiMap> dictMap = new HashMap<String, BidiMap>();
private static Logger logger = Logger.getLogger(DictEvalUtil.class);
public static void main loadConfig() {
loadConfig(fileName);
}
public static void loadConfig(String fileName) {
InputStream inputStream = null;
try {
ClassLoader cl = Configuration.class.getClassLoader();
if (cl != null) {
inputStream = cl.getResourceAsStream(fileName);
} else {
inputStream = ClassLoader.getSystemResourceAsStream(fileName);
}
SAXReader reader = new SAXReader();
Document document = reader.read(inputStream);
if (document != null) {
Element rootElement = document.getRootElement();
List<Element> dists = rootElement.elements("dictName");
for (Iterator<Element> iterator = dists.iterator(); iterator.hasNext();) {
Element dist = iterator.next();
String id = dist.attributeValue("id");
BidiMap tempMap = new DualHashBidiMap();//key与value可以互取
for (Iterator<Element> _iterator = dist.elementIterator(); _iterator.hasNext();) {
Element field = (Element) _iterator.next();
tempMap.put(field.attributeValue("srcVal"),
field.attributeValue("descVal"));
}
dictMap.put(id, tempMap);
}
} else {
logger.error("文件" + fileName + "不能解析");
}
} catch (Exception e) {
logger.error("", e);
if (inputStream != null) {
try {
inputStream.close();
inputStream = null;
} catch (IOException ex) {
logger.error("", ex);
}
}
} finally {
if (inputStream != null) {
try {
inputStream.close();
inputStream = null;
} catch (IOException ex) {
logger.error("", ex);
}
}
}
}
public static String srcTodesc(String key, String value) {
logger.debug("src2desc转义字典[" + key + "]=" + value);
if (StringHelper.isEmpty(key)) {
return "";
}
BidiMap map = (BidiMap) dictMap.get(key);
if (map == null) {
return value;
}
String descVal = (String) map.get(value);
if (descVal == null) {
return value;
}
return descVal;
}
public static String descTosrc(String key, String value) {
logger.debug("desc2src转义字典[" + key + "]=" + value);
if (StringHelper.isEmpty(key)) {
return "";
}
BidiMap map = (BidiMap) dictMap.get(key);
if (map == null) {
return value;
}
String srcVal = (String) map.getKey(value);
if (srcVal == null) {
return value;
}
return srcVal;
}
}