Posted on 2009-06-12 15:19
Gavin.lee 閱讀(436)
評論(0) 編輯 收藏 所屬分類:
xml doc 操作
長時間以來,一直使用properties作為配置文件,用著感覺也非常好。今天看到一篇文章讓我很受傷:“判斷一個程序系統(tǒng)的先進性,我們先看看他的配置文件,如果還在使用老套的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聯(lián)系起來,開始解析
parser.parse(confURL.toString(), handler);
// 獲取解析成功后的屬性 以后 我們其他應用程序只要調(diào)用本程序的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());
}

}