burgund
burgund

Reputation: 402

Update ConfigurationSection with Xpaths - what's the best way?

Since a few days i'm working with ConfigurationSection. I was dealing with multiple config files with different extensions. Making long story short, We've decided to store some configs as Xpaths, and the question is: what is the best way to update ConfigurationSection while having new values as Xpaths?

This code is working:

//section is an instance of ConfigurationSection, newConfig is an object with Xpath and value
var rawSectionXml = section.SectionInformation.GetRawXml(); 
XDocument sectionAsXml = null;
using (StringReader sr = new StringReader(rawSectionXml))
{
    using (XmlReader xmlReader = XmlReader.Create(sr))
    {
        sectionAsXml = XDocument.Load(xmlReader);
    }
}

var sectionAsXmlAttribute = ((IEnumerable<object>)sectionAsXml.XPathEvaluate(newConfig.XPath)).OfType<XAttribute>().FirstOrDefault();
sectionAsXmlAttribute.Value = newConfig.Value;
section.SectionInformation.SetRawXml(sectionAsXml.ToString());

Is there any simpler way of doing this? Is it possible to do the same without converting ConfigurationSection to XDocument?

Upvotes: 0

Views: 38

Answers (0)

Related Questions