保证类名/字段名和标签名一致即可(类名可首字母大写 自动转为小写)
/**
* @param xmlStr 字符串形式的xml
* @return 转换成功的OwnerInfo对象
* @throws DocumentException
* @throws IllegalAccessException
* @throws InstantiationException
*/
private OwnerInfo xmlStrToOwnerInfo(String xmlStr) throws DocumentException, IllegalAccessException, InstantiationException {
final Document resDoc = DocumentHelper.parseText(xmlStr);
final Element rootElement = resDoc.getRootElement();
final OwnerInfo ownerInfo = new OwnerInfo();
elementToObject(rootElement, ownerInfo);
log.info("根据返回xml生成对象为:{}",ownerInfo);
return ownerInfo;
}
/**
* 将该xml标签转换为java实体类 子标签作为属性填充,支持实体类中有对象字段(非String字段),递归转换
* @param rootElement xml的标签对象
* @param res 需要填充属性的对象
* @return 填充完属性的对象
* @throws IllegalAccessException
* @throws InstantiationException
*/
private Object elementToObject(Element rootElement, Object res) throws IllegalAccessException, InstantiationException {
String simpleName = res.getClass().getSimpleName();
final char first = simpleName.charAt(0);
if (Character.isUpperCase(first)) {
final char lowerCase = Character.toLowerCase(first);
simpleName = lowerCase + simpleName.substring(1);
}
final Element element = rootElement.element(simpleName);
final Field[] fields = res.getClass().getDeclaredFields();
for (final Field field : fields) {
field.setAccessible(true);
final Class<?> fieldType = field.getType();
if (fieldType.equals(String.class)) {
field.set(res, element.elementTextTrim(field.getName()));
} else {
final Object o = fieldType.newInstance();
final Object elementToObject = elementToObject(element, o);
field.set(res, elementToObject);
}
}
return res;
}