利用JDom读XML

在项目的src目录下建立一个gobal-configure.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<sys-configure>
	<jdbc-info>
		<driver-class>oracle.jdbc.driver.OracleDriver
		</driver-class>
		<url>jdbc:orcale:thin:@localhost:1521:zzg
		</url>
		<username>root</username>
		<password>123456</password>
	</jdbc-info>
	<beans>
		<bean id="com.yx.zzg.dao.UserDao" class="com.yx.dao.impl.UserDaoImpl" />
		<bean id="com.yx.zzg.dao.ItemDao" class="com.yx.dao.impl.ItemDaoImpl" />
	</beans>
</sys-configure>

读取xml
package com.yx.zzg.jdom;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;

public class ReadXML {
	private static ReadXML instance = new ReadXML();
	private static final String fileName = "gobal-configure.xml";
	Map<String, Object> map = new HashMap<String, Object>();
	private Element rootElt;

	private ReadXML() {
		SAXBuilder sb = new SAXBuilder();
		try {
			Document doc = sb.build(Thread.currentThread()
					.getContextClassLoader().getResourceAsStream(fileName));
			rootElt = doc.getRootElement();
			initJdbc();
			initBean();
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static ReadXML getInstance() {
		return instance;
	}

	private void initJdbc() {
		try {
			Element driverElt = (Element) XPath.selectSingleNode(rootElt,
					"//sys-configure/jdbc-info/driver-class");
			System.out.println(driverElt.getText());
			Element urlElt = (Element) XPath.selectSingleNode(rootElt,
					"//sys-configure/jdbc-info/url");
			System.out.println(urlElt.getText());
		} catch (JDOMException e) {
			e.printStackTrace();
		}
	}

	private void initBean() {
		try {
			List list = XPath
					.selectNodes(rootElt, "//sys-configure/beans/bean");
			for (Iterator<List> it = list.iterator(); it.hasNext();) {
				Element element = (Element) it.next();
				String id = element.getAttributeValue("id");
				String className = element.getAttributeValue("class");
				Object obj = Class.forName(className).newInstance();
				map.put(id, obj);
			}
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public Object getBean(Class c) {
		return map.get(c.getName());
	}
}

你可能感兴趣的:(java,oracle,xml,bean,jdbc)