import java.lang.reflect.Field;
import java.util.List;
import com.thoughtworks.xstream.XStream;
public class XmlUtil {
// 所有需要注册的类的配置,
public static final String CONFIGFILE = new GetClassPath()
.getMyConfigPath()
+ "/xml.prop";
private static XStream xs = null;
private static XmlUtil xmlUtil = null;
private XmlUtil() {
try {
// 获取所有需要与处理的java完整名
List list = FileUtil.readFile(CONFIGFILE);
//初始化xs
xs = alias(list);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 获得实例
* @return
*/
public static synchronized XmlUtil getInstance() {
if(null == xmlUtil){
xmlUtil = new XmlUtil();
}
return xmlUtil;
}
/**
* 根据类名做反射
*
* @param list
* 类完整名
* @return
* @throws ClassNotFoundException
*/
public XStream alias(List list) throws ClassNotFoundException {
XStream xs = new XStream();
for (int i = 0; i < list.size(); i++) {
Object obj;
try {
obj = Class.forName((String) list.get(i)).newInstance();
Class zz = obj.getClass();
aliasAtt(xs, zz);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return xs;
}
/**
* 对类进行xml解析配置
*
* @param xs
* @param z
* class对象
*/
public void aliasAtt(XStream xs, Class z) {
if (null == z) {
return;
}
// 类名注册
xs.alias(z.getSimpleName(), z);
Field[] field = z.getDeclaredFields();
// 类中成员变量注册,继承的不注册
for (int i = 0; i < field.length; i++) {
xs.aliasField(field[i].getName(), z, field[i].getName());
}
}
/**
* xml 格式字符串转换为对象
* @param str
* @return
*/
public Object xmlToObject(String str) {
return xs.fromXML(str);
}
/**
* 对象转换为xml格式字符串
* @param obj
* @return
*/
public String objToXml(Object obj) {
return xs.toXML(obj);
}
}
FileUtil.readFile()方法如下
/**
* 读取文件
*
* @param filePath
* 文件完整名
* @return 文件内容
* @throws IOException
*/
public static List readFile(String filePath) {
List list = new ArrayList();
FileInputStream fs = null;
InputStreamReader isr = null;
BufferedReader br = null;
try {
fs = new FileInputStream(filePath);
isr = new InputStreamReader(fs);
br = new BufferedReader(isr);
String data = "";
while ((data = br.readLine()) != null) {
list.add(data.trim());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (isr != null)
isr.close();
if (fs != null)
fs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return list;
}
Test
Printdata pd = new Printdata();
pd.setPrintFileList(printFileList);
pd.setAuto("1");
pd.setBillReceiver("billReceiver");
pd.setCustId("cust_id");
pd.setYear("2011");
pd.setMonth("11");
List list = FileUtil.readFile(XmlUtil.CONFIGFILE);
XmlUtil xmlUtil = XmlUtil.getInstance();
String xml = xmlUtil.objToXml(pd);//对象至xml
System.out.println(xml);
Printdata obj = (Printdata)xmlUtil.xmlToObject(xml);//xml至对象
需要的jar包见附件
下载次数: 1