您可以像这样通过 XStream 进行操作:
public static String getXMLFromObject(Object toBeConverted, String classNameAlias, Map<String, String> fieldAlias,
List<String> fieldsToBeOmitted) {
StringBuilder objectAsXML = new StringBuilder();
if(toBeConverted != null){
XStream xStream = new XStream(new DomDriver());
if(classNameAlias != null && classNameAlias != "" && classNameAlias.trim().length() > 0) {
xStream.alias(classNameAlias, toBeConverted.getClass());
}
if(fieldAlias != null && !fieldAlias.isEmpty()){
for (Entry<String, String> entry : fieldAlias.entrySet()) {
xStream.aliasField(entry.getKey(), toBeConverted.getClass(), entry.getValue());
}
}
if(fieldsToBeOmitted != null && fieldsToBeOmitted.size() > 0){
for (String fieldToBeOmitted : fieldsToBeOmitted) {
xStream.omitField(toBeConverted.getClass(), fieldToBeOmitted);
}
}
objectAsXML.append(xStream.toXML(toBeConverted));
}
return objectAsXML.toString();
}
如果您可以控制要转换为 XML 的类,那么我建议您有一个类似XMLConvertable
结构的接口
public interface XMLConvertable {
public String getClassAlias();
public List<String> getFieldToBeOmitted();
public Map<String, String> getFieldAliases();
}
在这种情况下,您不需要在上述方法中发送最后三个参数,只需从 获取它,objectToBeConverted
而且它更有意义,因为系统中的每个对象都可以声明自己是否可以转换为 XML。