一个用xml文件做配置的例子

发表于:2007-07-04来源:作者:点击数: 标签:
package org.devclub.util; /** * pTitle: 开发 者乐园社区/p * pDescription:读取XML配置文件 /p * pCopyright: Copyright (c) 2002/p * pCompany: devclub/p * @author 令少爷 * @version 0.9 */ import java .util.Properties; import javax.xml.parsers.*
package org.devclub.util;
/**
* <p>Title: 开发者乐园社区</p>
* <p>Description:读取XML配置文件 </p>
* <p>Copyright: Copyright (c) 2002</p>
* <p>Company: devclub</p>
* @author 令少爷
* @version 0.9
*/
import java.util.Properties;
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import org.w3c.dom.*;
import java.io.*;
public class ConfigXML {
    String xmlfile = "/conf/conf.xml";//配置文件路径
    DocumentBuilder db = null;
    DocumentBuilderFactory dbf = null;
    Document doc = null;
    String name = null;//配置项名称
    public ConfigXML() {
        dbf = DocumentBuilderFactory.newInstance();
    }
    public ConfigXML(String config_File) {
        xmlfile = config_File;
        dbf = DocumentBuilderFactory.newInstance();
    }
    /**
     * 读取配置信息
     * 这里会抛出异常
     */
    public void readConfig () throws ParserConfigurationException,IOException,SAXException {
        db = dbf.newDocumentBuilder();
        doc = db.parse(new File(xmlfile));
        echo(doc);
    }
    /**
     * 读取XML节点
     */
    private void echo(Node n) {
        int type = n.getNodeType();
        if (type == Node.ELEMENT_NODE) {
            name = n.getNodeName();//获得配置项名称
            NamedNodeMap atts = n.getAttributes();
            for (int i = 0; i < atts.getLength(); i++) {
                Node att = atts.item(i);
                echo(att);
            }
        }
        if (type == Node.TEXT_NODE) {
            printlnCommon(n);
        }
        for (Node child = n.getFirstChild(); child != null; child = child.getNextSibling()) {
            echo(child);//对节点做递归
        }
    }
    /**
     * 读取配置项值并将值保存到系统属性里
     */
    private void printlnCommon(Node n) {
        String val = n.getNodeValue();
        if ((val != null) && (!val.trim().equals(""))) {//屏蔽不必要的空值
            Properties properties = System.getProperties();
            properties.setProperty(name,val);
            System.setProperties(properties);
        }
    }
}
配置文件如下:
<?xml version="1.0" encoding="GB2312"?>
<site-app>
<jdbc>
  <jdbc-type>oracle</jdbc-type>
  <database-version>817</database-version>
  <driver-class>oracle.jdbc.driver.OracleDriver</driver-class>
  <jdbc-version>2.0</jdbc-version>
  <jdbc-url>jdbc:oracle:thin:@localserver:1521:cnxsl</jdbc-url>
  <database-name>cnxsl</database-name>
  <database-user>cnxs</database-user>
  <database-password>cnxs</database-password>
</jdbc>
</site-app>

可以随便在里面加任何值,如
<user>username</user>
这样不必修改这个ConfigXML.java文件,在你需要这个值时只需用这样一句来取就OK了:
System.getProperty("user");
是不是很简单?
注:我是用的sun的JAXP的标准库,也可很方便地改成ibm xml4j来处理。 

原文转自:http://www.ltesting.net