Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Update a XML file in C#? 1

Status
Not open for further replies.

Smitty020

MIS
Jun 1, 2001
152
US
I'm trying to update an XML file from C#

I have a filePath as a string.

<Model>
<Locations>
<BenefitsLocation>
<Name>Benfits Location</Name>
<FilePath>&quot;C:\\WhereEver&quot;</FilePath>
</BenefitsLocation>
</Locations>
</Model>

How would I got about updating this:
 
There are many solutions:
1.
- Load the xml file into a XmlDocument
- locate the element that you want to update
- update it (in memory) if found
- save the XmlDocument into the same xml file.
2.
-Load the xml file into a DataSet object (one line of code)
-Locate there the elements to be update
-Update the elemnents
-Save the DataSet object into the xml file (one line of code)

3. ///

Example :
Code:
bool bModified = false;
XmlDocument oXmlDocument = new XmlDocument();
oXmlDocument.Load(&quot;myfile.xml&quot;);
const string filePath = &quot;Model/Locations/BenefitsLocation/FilePath&quot;;
XmlNode n =oXmlDocument.SelectSingleNode(filePath))
if (n != null)
{
   n.InnerText = &quot;new path&quot;;
   bModified = true;
   
}
if (bModified)
    oXmlDocument.Save(&quot;myfile.xml&quot;);
-obislavu-
 
This is also thanks to Obislavu:

You can write a function which takes parameters the node name you want to set and the new value to put there.
This function locates the node for which you want to change its value, set the InnerText property to that value and calls Save().

void UpdateSettings(string key, string val)
{
try
{
XmlDocument oXmlDocument = new XmlDocument();
oXmlDocument.Load(&quot;settings.xml&quot;);
System.Xml.XmlNode n = oXmlDocument.SelectSingleNode(key);
if (n!=null)
{
n.InnerText= val;
}
//
oXmlDocument.Save(&quot;settings.xml&quot;);

}catch()
{
}
}

UpdateSettings(&quot;//router//name&quot;,myForm.nameTextBox1.Text);


The same but then as a function which takes a string from a form.

(this is Obislavu's code in my own thread about XML etc)

- Raenius

&quot;Free will...is an illusion&quot;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top