CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Apr 2011
    Posts
    58

    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.

  2. #2
    Join Date
    May 2011
    Location
    Washington State
    Posts
    220

    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");

  3. #3
    Join Date
    Apr 2011
    Posts
    58

    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

  4. #4
    Join Date
    May 2011
    Location
    Washington State
    Posts
    220

    Re: Rewrite one section of an xml file

    Quote Originally Posted by MrGibbage View Post
    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
  •  





Click Here to Expand Forum to Full Width

Featured