get Java Bean from XML - Java XML

Java examples for XML:XML Java Bean

Description

get Java Bean from XML

Demo Code


//package com.java2s;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    public static void main(String[] argv) throws Exception {
        System.out.println(getBean());
    }//  ww w .  ja v a  2  s. c o m

    public static Object getBean() {
        try {
            DocumentBuilderFactory dFactory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder builder = dFactory.newDocumentBuilder();
            Document doc;
            doc = builder.parse(new File(
                    "src/com/lihui/abstract_factory/config.xml"));

            NodeList nl = doc.getElementsByTagName("className");
            Node classNode = nl.item(0).getFirstChild();
            String cName = classNode.getNodeValue();

            @SuppressWarnings("rawtypes")
            Class c = Class.forName(cName);
            Object obj = c.newInstance();
            return obj;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

Related Tutorials