/**
* parseXmlToJavaBean(xm转JavaBean)
* Bean类及其属性需要添加XStreamAlias、XStreamAsAttribute注解与xml节点/属性名称匹配
*
* @param xml
* @param beanClass 转换的目标Bean
* @param ignoreFields 指定忽略的Bean属性或者属性内部属性
* @return T
* @throws @since 1.0.0
*/
@SuppressWarnings("unchecked")
public static <T> T parseXmlToJavaBean(String xml, Class<?> beanClass, List<String> ignoreFields) {
// 转换的目标Bean
T javaBean = null;
XStream xStream = new XStream(new DomDriver()) {
@Override
protected MapperWrapper wrapMapper(MapperWrapper next) {
return new MapperWrapper(next) {
@Override
@SuppressWarnings("rawtypes")
public boolean shouldSerializeMember(Class definedIn, String fieldName) {
if (null != ignoreFields && ignoreFields.contains(fieldName)) {
return false;
}
return super.shouldSerializeMember(definedIn, fieldName);
}
};
}
};
// 启用注解
xStream.processAnnotations(beanClass);
//忽略未知节点
xStream.ignoreUnknownElements();
registerConverter(xStream);
// 执行xmlString-->Bean转换
javaBean = (T) xStream.fromXML(xml);
return javaBean;
}