public void EditCarsXml() { var appConfigFilePath = string.Concat(Assembly.GetExecutingAssembly().Location, ".config"); var appConfigWriterSettings = new ConfigModificatorSettings("//appSettings", "//add[@key='{0}']", appConfigFilePath); var value = ConfigurationManager.AppSettings["testKey1"]; Console.WriteLine("Value before modification: {0}", value); ConfigModificator.ChangeValueByKey( key: "testKey1", value: "ChangedValueByModificator", attributeForChange: "value", configWriterSettings: appConfigWriterSettings); ConfigModificator.RefreshAppSettings(); value = ConfigurationManager.AppSettings["testKey1"]; Console.WriteLine("Value after modification: {0}", value); //Example how to change Custom XML configuration var carsConfigFilePath = "Cars.xml"; var carsConfigWriterSettings = new ConfigModificatorSettings("//cars", "//car[@name='{0}']", carsConfigFilePath); ConfigModificator.ChangeValueByKey( key: "BMW", value: "Mazda", attributeForChange: "name", configWriterSettings: carsConfigWriterSettings); }
public static void ChangeValueByKey(string key, string value, string attributeForChange, ConfigModificatorSettings configWriterSettings) { XmlDocument doc = ConfigModificator.LoadConfigDocument(configWriterSettings.ConfigPath); XmlNode rootNode = doc.SelectSingleNode(configWriterSettings.RootNode); if (rootNode == null) { throw new InvalidOperationException("the root node section not found in config file."); } try { XmlElement elem = (XmlElement)rootNode.SelectSingleNode(string.Format(configWriterSettings.NodeForEdit, key)); elem.SetAttribute(attributeForChange, value); doc.Save(configWriterSettings.ConfigPath); } catch (Exception ex) { throw ex; } }