java xml作為設定檔,讀取

來源:互聯網
上載者:User

  每個項目都需要設定檔來把可變的東西抽出來,方便程式的開發和維護:

  自己編寫了一個xml檔案讀取類,並可以以字串形式調用xml檔案中的屬性與其值,其實也可以,直接一個static函數直接獲得屬性與其值,然而,我沒這麼做。估計這麼做會更好。不多說,就算是改也容易。先把source提供出來:

/* * Property.java * * Created on 2008.7.11, am8:56 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */package mail;import java.io.File;import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList;/** * * @author user */public class Property {        private Element _rootElement = null;    /** Creates a new instance of Property */    public Property() {        //get the current directory        File directory = new File("");        String pathStr = directory.getAbsolutePath();        try {             DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();            DocumentBuilder builder = factory.newDocumentBuilder();            Document document = builder.parse(new File(pathStr + "//" + CONSTANT.xmlFileName));            _rootElement = document.getDocumentElement();        } catch (Exception e) {            Logger.println("exception:" + e.getMessage());        }    }        /* get property with the specified name     * param: property name     * return: the value of the property     */    public String getProperty(String propertyName){        try{            NodeList list = _rootElement.getElementsByTagName(propertyName);            if(list.getLength() == 0){throw new Exception("xml error: there is no such property /"" + propertyName + "/"");}            Element element = (Element) list.item(0);            return element.getChildNodes().item(0).getNodeValue();        }catch(Exception ex){            Logger.println(ex.getMessage());            return "";        }    }        /* factory of this class     * return the object of this class     */    public static Property getInstance(){        Property _property = new Property();        return _property;    }    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.