Java XML Node Value xmlToBean(Node beanNode)

Here you can find the source of xmlToBean(Node beanNode)

Description

xml To Bean

License

Open Source License

Declaration

public static Object xmlToBean(Node beanNode) throws ClassNotFoundException, IllegalAccessException,
        InstantiationException, NoSuchMethodException, InvocationTargetException 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

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   ww w  .j  av  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

  1. setTextValue(Node node, String value)
  2. setValueOfNode(Node node, String value)
  3. xmlGetFirstTextValue(Node node)
  4. xmlGetText(Node node)
  5. xmlNodeGetValue(Node node)