2012-03-13 85 views
1

我已經使用Configuration Section Designer(csd)爲我的應用程序生成xml配置文件。使用csd生成的xml的讀取/寫入

現在,我想用這個XML文件(在C#)的工作,做兩件事情:

讀取特定值(其外地搜索),像

txtbox_username.Text = ConfigurationManager.AppSettings["userName"]; 

2.寫入特定值,像

config.AppSettings.Settings["userName"].Value = txtbox_username.Text; 

config.Save(ConfigurationSaveMode.Modified); 

ConfigurationManager.RefreshSection("configuration"); 
  • PS:這是我執行如何讀取正規的XML文件/寫,看起來像這樣:

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
    <appSettings> 
add key="userName" value="Value1" 
    </appSettings> 
</configuration> 

但CSD生成的XML看起來不同...

<?xml version="1.0"?> 
<configuration> 
    <configSections> 
    <section name="sectionName" type="Sample.ConfigurationSection.sectionName, Sample.ConfigurationSection, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/> 
    </configSections> 
    <sectionName xmlns="Sample.ConfigurationSection"> 
    <logFile debugLevel="3" filePath="c:\new" maxFileCount="10" maxFileLength="1000"/> 
    <results path="C:\Results"/> 
    <details user="blabla" pass="12345" code="abc"/> 
    <stuff fromAddress="[email protected]" toAddress="[email protected]" sendMail="true""/> 
    </sectionName> 
    <startup> 
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/> 
    </startup> 
</configuration> 

在這裏,我想編輯和保存,例如,用戶/密碼/代碼字段。

回答

0

總之(以及使用這些擴展:http://searisen.com/xmllib/extensions.wiki),你可以做到這一點讀/寫用戶,

XElement file = XElement.Load(xmlFile); 
XNamespace ns = "Sample.ConfigurationSection"; 
XElement section = file.GetElement(ns + "sectionName"); 
string user = section.Get("details/user", string.Empty); 
section.Set("details/user", "bubba", true); // true = set as attribute 
file.Save(xmlFile);