dom4j 反射,xml转对象

保证类名/字段名和标签名一致即可(类名可首字母大写 自动转为小写)

	/**
     * @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;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值