Rewrite one section of an xml file
If I have an XML file with several sections, is there an easy way to rewrite just one section of it?
Say I have
<settingsFile>
<section1>
<element />
</section1>
<section2>
<element />
</section2>
</settingsFile>
I just want to rewrite section2, for instance. I suppose I need to load the file into memory, such as an XmlDoc, look for the section in question, delete it, create the new section, and then merge the new section into the XmlDoc?? The problem is, I can't figure out how to merge one section into an existing xml structure.
Re: Rewrite one section of an xml file
If you just load it into the XmlDoc, I think you can simply select the node and edit the values you wish, then XmlDoc.Save() it over the old one... like so....
Considering the following XML...
Code:
<?xml version="1.0" encoding="utf-8"?>
<xml>
<section1>
<value>three</value>
</section1>
<section2>
<value>two</value>
</section2>
</xml>
You can update it this way...
Code:
// load an xml document ...
XmlDocument doc = new XmlDocument();
doc.Load(@"j:\test2.xml");
// change an element value...
XmlNode sec1Value = doc.SelectSingleNode("xml/section1/value");
sec1Value.InnerText = "one";
// save the xml...
doc.Save(@"j:\test2.xml");
Re: Rewrite one section of an xml file
That totally makes sense. I always used .InnerText to read data, so I... ahem.. *assumed* it was read-only. *sigh*
Thanks :)
Re: Rewrite one section of an xml file
Quote:
Originally Posted by
MrGibbage
That totally makes sense. I always used .InnerText to read data, so I... ahem.. *assumed* it was read-only. *sigh*
Thanks :)
lol.. I understand, I've made plenty of assumptions myself... :) Glad to be of help.