答案: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来处理。
上一个:Java开发工具与开发环境问答集(java新手推荐)
下一个:关于override和overload的.请各位补充指正.