The original xml like below.
<configuration>
<configSections>
<sectionname=“TestReadSection” type=“System.Configuration.NameValueSectionHandler“ />
<sectionname=“TestWriteSection” type=“System.Configuration.ClientSettingsSection“allowExeDefinition=“MachineToLocalUser“requirePermission=“false“ />
</configSections>
<TestReadSection>
<addkey=“ApplicationName” value=“Configuration Demo“ />
</TestReadSection>
<TestWriteSection>
<settingname=“ConnectionMachine” value=“nostring“>
<value>somevalue</value>
</setting>
</TestWriteSection>
</configuration>
The code segment below change the value element and TestWriteSection child’s attributes.
staticvoid Main(string[] args)
{
string strDir = Directory.GetCurrentDirectory(); //
strDir = Directory.GetParent(strDir).ToString();
strDir = Directory.GetParent(strDir).ToString() + @”\App.config”;
string newConnectionString = @”Server=local;Database=” + “Northwind” + “;Trusted_Connection=true”;
XmlDocument xDoc = newXmlDocument();
xDoc.Load(strDir);
//update value ekement
XmlNodeList nodeList = xDoc.GetElementsByTagName(“value”);
nodeList[0].InnerXml = “zzz”;
//update TestWriteSection element
XmlNodeList nodeList1 = xDoc.GetElementsByTagName(“TestWriteSection”);
XmlNodeList nodeAppSettings = nodeList1[0].ChildNodes;
XmlAttributeCollection xmlAttCollection = nodeAppSettings[0].Attributes;
xmlAttCollection[0].InnerXml = “ConnectionName”; // for key attribute
xmlAttCollection[1].InnerXml = newConnectionString; // for value attribute
xDoc.Save(strDir); // saves the web.config file
}
}
After running the code then the xml file will change to following.
<configuration>
<configSections>
<sectionname=“TestReadSection” type=“System.Configuration.NameValueSectionHandler“ />
<sectionname=“TestWriteSection” type=“System.Configuration.ClientSettingsSection” allowExeDefinition=“MachineToLocalUser” requirePermission=“false“ />
</configSections>
<TestReadSection>
<addkey=“ApplicationName” value=“Configuration Demo“ />
</TestReadSection>
<TestWriteSection>
<settingname=“ConnectionName” value=“Server=local;Database=Northwind;Trusted_Connection=true“>
<value>zzz</value>
</setting>
</TestWriteSection>
</configuration>
You can also download a single solution from http://skydrive.live.com. The sample file name is ConAppXmlDocument.rar. My MSN ID ischanmmn@hotmail.com.
Resources:
http://geekswithblogs.net/AzamSharp/archive/2005/10/09/56457.aspx
Pingback: How to read from XML document using XMLDocument | Chanmingman's Blog