user3405204
user3405204

Reputation: 21

how to modify xml node using c#

have that xml file :

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
 <applicationSettings>
  <AllSettings>
   <setting name="setting1" serializeAs="String">
    <value>myValue</value>
   </setting>
  </AllSettings>
 </applicationSettings>
</configuration>

and i want to change the value of <value> into something else, i have tried a couple method but can't find attribute <value>

Upvotes: 0

Views: 1242

Answers (2)

w.b
w.b

Reputation: 11238

You can use XElement.ReplaceWith:

XDocument doc = XDocument.Load("data.xml");
XElement value = doc.Root.Descendants("value").SingleOrDefault();

value.ReplaceWith(new XElement("value", "newValue"));

doc.Save("data.xml");

or, as the other answer suggested, XElement.SetValue:

value.SetValue("newValue");

Upvotes: 3

Robert Hegner
Robert Hegner

Reputation: 9396

You can load your XML in a XDocument object (System.Xml.Linq namespace) and then change the value like this:

// load XML from string:
var xdoc = XDocument.Parse(xml);
// or load XML from file:
var xdoc = XDocument.Load("filename.xml");

// change value
xdoc.Root.Element("applicationSettings").Element("AllSettings").Element("setting").Element("value").SetValue("myNewValue");

Upvotes: 1

Related Questions