Java examples for XML:XML Java Bean
get Bean from XML
//package com.java2s; 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 = "java2s.com"; String nodeName = "java2s.com"; System.out.println(getBean(relativePath, nodeName)); }//from ww w . j a v a 2 s .c o m 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; } } }