近来遇到的编程过程中需要对XML进行大量的处理,java是面向对象的,所以要把XML的处理转化为面向对象的处理.下面记录下我用XStream进行XML与对象的转换过程.
public class XmlUtils {
private static XStream xstream;
static {
xstream = new XStream(new DomDriver("UTF-8", new XmlFriendlyNameCoder("-_", "_")));
}
/**
* XML to object.
*
* @param inputXml
* XML string.
* @param types
* annotation classes.
* @return
* @throws Exception
*/
public static Object xml2Object(String inputXml, Class< >[] types) throws Exception {
if (null == inputXml || "".equals(inputXml)) {
return null;
}
xstream.processAnnotations(types);
return xstream.fromXML(inputXml);
}
/**
* object to XML.
*
* @param ro
* Object.
* @param types
* annotation classes.
* @return
* @throws Exception
*/
public static String object2Xml(Object ro, Class< >[] types) throws Exception {
if (null == ro) {
return null;
}
xstream.processAnnotations(types);
return xstream.toXML(ro);
}
}
对生成xml中__替换_的最新写法是:xstream = new XStream(new DomDriver("UTF-8", new XmlFriendlyNameCoder("-_", "_")));
网上很多用这种XStream xstream = new XStream(new XppDriver(new XmlFriendlyReplacer("-_", "_")));
帮助文档上明确写明
/**
* @since 1.2
* @deprecated As of 1.4, use {@link #DomDriver(String, NameCoder)} instead.
*/
说明1.4已经废弃了这种做法.
处理过程中都用了annotations来处理对象,下面是其中一个对象的例子
import com.thoughtworks.xstream.annotations.XStreamAlias;
@XStreamAlias("RESULT")
public class ResultObject {
@XStreamAlias("RTNCODE")
private String rtncode;
@XStreamAlias("MESSAGE")
private String message;
@XStreamAlias("CONTENT")
private Content content;
...省略了get, set方法
下面是使用XmlUtils 的测试例子
try {
Class< >[] types = new Class[] { ResultObject.class, Content.class};
resultXml = XmlUtils.object2Xml(ro, types);//其中ro是要转换的对象
System.out.println(resultXml);
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
//下面是转换xml成对象的测试代码
InputObject io = (InputObject) XmlUtils.xml2Object(str, new Class[] { InputObject.class });
其中str是xml格式字符串.