Java 怎么从XML获取bean

2019年8月9日22:19:46Java 怎么从XML获取bean已关闭评论 483 1390字阅读4分38秒

1.简介

Java 怎么从XML获取bean?——请看下文。

2.示例代码

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


import java.io.File;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import org.w3c.dom.NodeList;

public class Main {
    public static void main(String[] argv) throws Exception {
        String relativePath = "tah1986.com";
        String nodeName = "tah1986.com";
        System.out.println(getBean(relativePath, nodeName));
    }

    private static String path = System.getProperty("user.dir")
            + "/src/org/design/pattern/";

    public static Map<String, Object> getBean(String relativePath,
            String nodeName) {
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            DocumentBuilderFactory dFactory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder builder = dFactory.newDocumentBuilder();
            Document doc;
            doc = builder.parse(new File(path + relativePath));

            NodeList documents = doc.getElementsByTagName(nodeName);
            System.out.println(documents.getLength());
            for (int i = 0; i < documents.getLength(); i++) {
                Element element = (Element) documents.item(i);
                String type = element.getElementsByTagName("type").item(0)
                        .getFirstChild().getNodeValue().trim();
                String className = element
                        .getElementsByTagName("className").item(0)
                        .getFirstChild().getNodeValue().trim();
                Class clazz = Class.forName(className);
                Object obj = clazz.newInstance();
                map.put(type, obj);
            }
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

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