天天看點

C#對xml檔案的基本操作

1、建立如下xml檔案(xml代碼)。

<?xml version="1.0" encoding="utf-8" ?> 

<config> 

    <userName></userName> 

    <biography></biography> 

</config> 

2、給userName添加資料(C#代碼),值得注意的是這裡如果用xmlDoc.GetElementById會傳回null,至少在IE9下是這樣的,是以才用了xmlDoc.GetElementsByTagName。

XmlDocument xmlDoc = new XmlDocument();  

xmlDoc.Load(Server.MapPath("虛拟路徑"));  

XmlNodeList nodeList = xmlDoc.GetElementsByTagName("userName");  

/*若要存儲html代碼,可将下面一句改為:  

**nodeList[0].InnerXml = "<![CDATA[" + "html代碼" + "]]>";  

*/ 

nodeList[0].InnerText = "張山";  

xmlDoc.Save(Server.MapPath("虛拟路徑")); 

3、讀取userName的資料(C#代碼)。

/*下面假定将内容讀到Literal1裡面*/ 

Literal1.Text = nodeList[0].InnerText; 

***

本文轉自walker snapshot部落格51CTO部落格,原文連結http://blog.51cto.com/walkerqt/846153如需轉載請自行聯系原作者

RQSLT