Posted on 2009-06-12 15:19
Gavin.lee 阅读(430)
评论(0) 编辑 收藏 所属分类:
xml doc 操作
长时间以来,一直使用properties作为配置文件,用着感觉也非常好。今天看到一篇文章让我很受伤:“判断一个程序系统的先进性,我们先看看他的配置文件,如果还在使用老套的xxx=123 这样类似.ini的文件,我们也许会微微一笑,他又落伍了.....”,竟然有这种说法,呵,立马google了一下,都说xml做配置文件是大势所趋。 先来试试手,找了个比较精辟的。
<?xml version="1.0" encoding="UTF-8"?>
<xml>
<driver>driver</driver>
<name>name</name>
</xml>
package com.Gavin.xml;

import java.util.Properties;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.net.URL;


public class ParseXml
{

// 定义一个Properties 用来存放 dbhost dbuser dbpassword的值
private Properties props;

// 这里的props

public Properties getProps(String filename) throws Exception
{
this.parse(filename);
return this.props;
}


public void parse(String filename) throws Exception
{

// 将我们的解析器对象化
ConfigParser handler = new ConfigParser();

// 获取SAX工厂对象
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(false);
factory.setValidating(false);

// 获取SAX解析
SAXParser parser = factory.newSAXParser();

// 得到配置文件myenv.xml所在目录. tomcat中是在WEB-INF/classes
// 下例中BeanConstants是用来存放xml文件中配置信息的类,可以自己代替或定义
URL confURL = this.getClass().getClassLoader().getResource(filename);
// URL confURL = BeanConstants.class.getClassLoader().getResource(filename);

try
{
// 将解析器和解析对象myenv.xml联系起来,开始解析
parser.parse(confURL.toString(), handler);
// 获取解析成功后的属性 以后 我们其他应用程序只要调用本程序的props就可以提取出属性名称和值了
props = handler.getProps();

} finally
{
factory = null;
parser = null;
handler = null;
}
}

public static void main(String args[])
{

try
{
ParseXml px = new ParseXml();
Properties props = px.getProps("db.xml");
System.out.println(props.getProperty("driver"));
System.out.println(props.getProperty("name"));
System.out.println(props.get("china"));

} catch (Exception e)
{
e.printStackTrace();
}
}
}


class ConfigParser extends DefaultHandler
{

// //定义一个Properties 用来存放 dbhost dbuser dbpassword的值
private Properties props;

private String currentSet;

private String currentName;

private StringBuffer currentValue = new StringBuffer();

// 构建器初始化props

public ConfigParser()
{
this.props = new Properties();
}


public Properties getProps()
{
return this.props;
}

// 定义开始解析元素的方法. 这里是将<xxx>中的名称xxx提取出来.
public void startElement(String uri, String localName, String qName,

Attributes attributes) throws SAXException
{
currentValue.delete(0, currentValue.length());
this.currentName = qName;

}

// 这里是将<xxx></xxx>之间的值加入到currentValue

public void characters(char[] ch, int start, int length)

throws SAXException
{

currentValue.append(ch, start, length);

}

// 在遇到</xxx>结束后,将之前的名称和值一一对应保存在props中

public void endElement(String uri, String localName, String qName)

throws SAXException
{

props.put(qName.toLowerCase(), currentValue.toString().trim());
}

}