It is easy to read an XML file and get the exact Node Text, but how do I Update that Node with a new value?
To read:
public static String GetSettings(SettingsType type, SectionType section) { XmlTextReader reader = new XmlTextReader(HttpContext.Current.Request.MapPath(APPSETTINGSPATH)); XmlDocument document = new XmlDocument(); document.Load(reader); XmlNode node = document.SelectSingleNode( String.Format('/MyRootName/MySubNode/{0}/{1}', Enum.Parse(typeof(SettingsType), type.ToString()), Enum.Parse(typeof(SectionType), section.ToString()))); return node.InnerText; }
to write …?
public static void SetSettings(SettingsType type, SectionType section, String value) { try { XmlTextReader reader = new XmlTextReader(HttpContext.Current.Request.MapPath(APPSETTINGSPATH)); XmlDocument document = new XmlDocument(); document.Load(reader); XmlNode node = document.SelectSingleNode( String.Format('/MyRootName/MySubNode/{0}/{1}', Enum.Parse(typeof(SettingsType), type.ToString()), Enum.Parse(typeof(SectionType), section.ToString()))); node.InnerText = value; node.Update(); } catch (Exception ex) { throw new Exception('Error:', ex); } }
Note the line, node.Update(); does not exist, but that’s what I wanted 🙂
I saw the XmlTextWriter object, but it will write the entire XML to a new file, and I just need to update one value in the original Node, I can save as a new file and then rename the new file into the original name but… it has to be simpler to do this right?
Any of you guys have a sample code on about to do this?
Thank you
You don’t need an ‘update’ method – setting the InnerText property updates it. However, it only applies the update in memory. You do need to rewrite the whole file though – you can’t just update a small part of it (at least, not without a lot of work and no out-of-the-box support).