Convert xml To Java Bean - Java XML

Java examples for XML:XML Java Bean

Description

Convert xml To Java Bean

Demo Code


//package com.java2s;

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());
                }/*from w w w.  jav  a2 s.  c  o m*/
            }
        }
        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();
    }
}

Related Tutorials