abramlimpin
abramlimpin

Reputation: 5077

C#/XML: Change/Replace data from an XML file via textbox

I have a XML file which contains the following:

<config>
  <webservices>
     <webservice>
       <name>A</name>
       <value>http://www.123.com</value>
     </webservice>
     <proxy enabled="false" useiedefault="false">
       <name>
       </name>
       <value>
       </value>
     </proxy>
  </webservices>
</config>

Is there a way to change the values of 'webservice value' (from the XML file) through textbox in C# and save/update it afterwards?

TextBox1.Text = "http://www.abc.com";
// change value of xml

Upvotes: 3

Views: 2818

Answers (2)

Steve
Steve

Reputation: 31

I was getting a "File already opened by something else" type error.

This is your code that I modified and now it works for me:

StreamReader fileStream = new StreamReader(filename);

var doc = new XmlDocument();

doc.Load(fileStream);

var node = doc.SelectSingleNode(@"config/webservices/webservice/value");

node.InnerText = TextBox1.Text;

fileStream.Close();

doc.Save(fileName);

Upvotes: 3

Alex Humphrey
Alex Humphrey

Reputation: 6219

This code fragment should work, where fileName is the full path to your XML file:

var doc = new XmlDocument();
doc.Load(fileName);
var node = doc.SelectSingleNode(@"config/webservices/webservice/value");
node.InnerText = TextBox1.Text;
doc.Save(fileName);

Upvotes: 1

Related Questions