XML設定檔的讀取(sax)

來源:互聯網
上載者:User

在最近的一個MIS項目中,為了避免寫入程式碼,我需要把一些配置資訊寫在一個設定檔中.考慮到是J2EE項目,J2EE的設定檔
好像都是xml檔案了,再用傳統ini檔案是不是有點落伍了?
ok,就用xml做設定檔吧.
我的設定檔reportenv.xml如下,比較簡單:

<?xml version="1.0" encoding="utf-8"?>
<reportenv>
<datasource>
<username>sqlname</username>
<password>password</password>
</datasource>
</reportenv>

現在的問題是我用什麼來讀取配置資訊?
現在流行的是dom4j和sax,我以前一直用dom4j.可是weblogic workshop內建的是sax,我又不想再引入包了,於是就是sax吧.
第一步:ConfigParser.java
/*
 * Create Date: 2005-6-13
 * Create By: 板橋裡人
 * purpose:xml設定檔屬性讀取器
 */
package com.infoearth.report;

import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.SAXException;
import java.util.Properties;

public class ConfigParser extends DefaultHandler {

    ////定義一個Properties 用來存放屬性值
    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());
        }

    }
   
 第二步:ParseXML.java
 /*
 * Create Date: 2005-6-13
 * Create By: 板橋裡人 李春雷修改
 * purpose:xml設定檔屬性讀取器(通用),
 */
 
package com.infoearth.report;

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

public class ParseXML{
    //定義一個Properties 用來存放屬性值
    private Properties props;

    public Properties getProps() {
        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();
        try{
            //將解析器和解析對象xml聯絡起來,開始解析
            parser.parse(filename, handler);
            //擷取解析成功後的屬性
            props = handler.getProps();
            }finally{
                factory=null;
                parser=null;
                handler=null;
                }
        }
    }
第三步:ReadConfigXml.java
/*
 * Create Date: 2005-6-13
 * Create By: 李春雷
 * purpose:xml設定檔屬性讀取器
 */

package com.infoearth.report;

import java.util.Properties;

public class ReadConfigXml
{
    private Properties props;
   
    public ReadConfigXml(String url){
  ParseXML myRead = new ParseXML();
   try {
    myRead.parse(url);
                props = new  Properties();
                props = myRead.getProps();
   } catch (Exception e) {
    e.printStackTrace();
   }     
        }
   public  String getUserName(){
        return props.getProperty("username");
        }       
   public String getPassWord(){
        return props.getProperty("password");
    }

}

ok,搞定了,讀取的時候如下:
ReadConfigXml xmlread = new ReadConfigXml("reportenv.xml");
String username = xmlread.getUserName();
String password = xmlread.getPassWord();

前兩個類實現了xml文件屬性設定的任意讀取.只要是xml的屬性值,都讀到了property中,你只需在property中提取就可以了.
第三個類是我針對我的xml檔案寫的,似乎有點多餘.呵呵.其實有難言之隱.因為不想過多的改動以前的程式架構,就畫蛇添
足了一下.

另外,感謝j道,感謝板橋裡人.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.