|
-
August 7th, 2011, 07:10 PM
#1
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.
-
August 8th, 2011, 05:31 PM
#2
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");
-
August 8th, 2011, 09:48 PM
#3
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
-
August 9th, 2011, 12:48 PM
#4
Re: Rewrite one section of an xml file
 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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|