xml 檔案讀取 及配置

2021-05-21 12:24:11 字數 1948 閱讀 3765

在開發應用程式過程中,為了移植方便,我們常常將一些公用的東西寫到xml檔案中進行配置,比如:連線資料庫的一些引數,需要讀取的檔案路徑,常用表名稱等等。那麼怎樣從xml檔案中讀取和寫入這些內容呢?下邊介紹一下用saxreader類的操作

(本文感謝好朋友賀永明的幫助)

xml檔案操作類:

public class xmloperate

catch (ioexception e)

return false;

}/**

* * @param filename

*            配置檔案名稱

* @return 配置檔案對應的document

*/public static document getdocumenttree(string filename)

catch (documentexception e)

return doc;

}/**

* 獲取將要生成哦初始化配置

* * @param filepath

*            檔案路徑

* @param filename

*            檔名

* @return 返回element

*/public static element getinitelement(string filepath, string filename) else

saxreader reader = new saxreader();

reader.setencoding("gb2312");

file f = new file(fullname);

try catch (documentexception e)

root = doc.getrootelement();

return root;}}

配置資訊獲取類 :

public class configoperater

/*** 獲取配置資訊

* @date 2010-1-12

* @time 上午09:23:41

* @param filename 配置檔案名稱

* @param tagname 配置檔案標籤

* @return

*/public static string getconfigmessage(string filename ,string tagname)

}配置檔案為:config.xml

e檔案4

cz1200

30system,valueinfo,yxvalueinfo,

d:/scadadataftp/czreal

d:/scadadataftp/czhistory

czreal

hbpgsis_monitor

oracle(thin)

jdbc:oracle:thin:@127.0.0.1:1521:imsbase

oracle.jdbc.driver.oracledriver

hbpgmis_monitor

hbpgmis_monitor

hbpgmis_monitor

hbpgmis_monitor

其中節點下的子節點可以直接獲取到節點的內容。

下的節點內容是單獨獲取的。這裡只是簡單的將我在專案中用過的檔案作例子,讀者可以舉一反三,自己寫檔案測試

測試類public class test

public static void main(string args){

// 獲取節點 的內容

string str = null;

str = configoperater.getconfigmessage("config.xml","projectname");

system.out.println("str:"+str);

控制台顯示:

str:e檔案

讀取XML檔案

private void button2 click object sender,eventargs e using filestream fs new filestream filename,filemode.open,fileaccess.read n xl.name 是否有屬性 if xl.h...

xml檔案讀取

xml檔案讀取 利用庫tinyxml 示例xml 獲取對應路徑上的xml if document null tixmlelement nodeelement document rootelement 獲取根節點 tixmlelement objectelement nodeelement first...

Xml配置檔案的資料讀取

在開發中的可變配置項常使用xml檔案的方式進行配置和讀取 假設下面有乙個配置檔案 00001 喜羊羊小學 虹口區水電路120號 0001 一年級一班 50 0002 一年級二班 40這些配置項是可變的,用於專案中的可變配置項,我們使用xmldocument,xmlelement,xmlnodelis...