Java 怎么将XML转换为JavaBean

2019年8月9日22:20:34Java 怎么将XML转换为JavaBean已关闭评论 539 1234字阅读4分6秒

1.简介

Java 怎么将XML转换为JavaBean?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */



import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.lang.reflect.InvocationTargetException;

public class Main {

    public static Object xmlToBean(Node beanNode)
            throws ClassNotFoundException, IllegalAccessException,
            InstantiationException, NoSuchMethodException,
            InvocationTargetException {
        String className = beanNode.getNodeName();
        System.out.println(className);
        Class clazz = Class.forName(className);
        Object bean = clazz.newInstance();
        NodeList fieldNodeList = beanNode.getChildNodes();
        for (int i = 0; i < fieldNodeList.getLength(); i++) {
            Node fieldNode = fieldNodeList.item(i);
            if (fieldNode.getNodeType() == Node.ELEMENT_NODE) {
                String fieldName = fieldNode.getNodeName();
                if (!fieldName.contains(".")) {
                    String getName = analyzeMethodName(fieldName, "get");
                    String setName = analyzeMethodName(fieldName, "set");
                    System.out.println(setName);
                    clazz.getMethod(setName,
                            clazz.getMethod(getName).getReturnType())
                            .invoke(bean, fieldNode.getTextContent());
                }
            }
        }
        System.out.println(bean);
        return bean;
    }

    private static String analyzeMethodName(String fieldName,
            String methodType) {
        StringBuilder getName = new StringBuilder(methodType);
        return getName.append(
                String.valueOf(fieldName.charAt(0)).toUpperCase()
                        + fieldName.substring(1)).toString();
    }
}

 
继续阅读
编程十万个怎么办