XML配置文件内容如下:
<?xml version="1.0" encoding="UTF-8"?> <config> <db-info> <driver-name>oracle.jdbc.driver.OracleDriver</driver-name> <url>jdbc:oracle:thin:@127.0.0.1:1521:ORCL</url> <username>username</username> <password>password</password> </db-info> </config> ?
读取XML程序如下,利用单例模式:
package com.king.drp.util; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; /** * 采用单例模式读取xml配置文件sys-config.xml * @author lijike * */ public class ConfigReader { //静态的私有成员变量 private static ConfigReader instance = new ConfigReader(); //公共的静态入口方法 public static ConfigReader getInstance() { return instance; } private Document doc; private JdbcInfo jdbcInfo; public JdbcInfo getJdbcInfo() { return jdbcInfo; } //私有的构造方法 private ConfigReader() { try { doc = new SAXReader().read(Thread.currentThread().getContextClassLoader().getResourceAsStream("sys-config.xml")); Element driverNameElt = (Element)doc.selectObject("/config/db-info/driver-name"); Element urlElt = (Element)doc.selectObject("/config/db-info/url"); Element usernameElt = (Element)doc.selectObject("/config/db-info/username"); Element passwordElt = (Element)doc.selectObject("/config/db-info/password"); jdbcInfo = new JdbcInfo(); jdbcInfo.setDriverName(driverNameElt.getStringValue()); jdbcInfo.setUrl(urlElt.getStringValue()); jdbcInfo.setUsername(usernameElt.getStringValue()); jdbcInfo.setPassword(passwordElt.getStringValue()); } catch (DocumentException e) { e.printStackTrace(); } } }
?