get Class From XML via DOM - Java XML

Java examples for XML:DOM

Description

get Class From XML via DOM

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(getClassFromXML());
    }/*from   w  ww.ja  v  a 2  s  .  com*/

    public static Object getClassFromXML() throws Exception {
        //create DOM object
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document document = docBuilder.parse(new File("property.xml"));

        //get the node name and get the class name
        NodeList nodeList = document.getElementsByTagName("className");
        Node node = nodeList.item(0).getFirstChild();
        String className = node.getNodeValue();

        //return an object through the class name
        Class tempClass = Class.forName(className);
        Object object = tempClass.newInstance();
        return object;
    }
}

Related Tutorials