Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to change the value of an element in C#

Tags:

c#

.net

xml

I'm trying to look at the best way of changing the value of an element in XML.

<MyXmlType>
   <MyXmlElement>Value</MyXmlElement>
</MyXmlType>

What is the easiest and/or best way to change "Value" in C#?

I've looked at XMLDocument and it will cause a load of the whole XML document to memory. Could you do it safely with the XMLReader. The problem is changing the value and emitting it back seems like an interesting conundrum.

Cheers :D

like image 585
Spence Avatar asked Feb 13 '09 01:02

Spence


People also ask

Can you change array values in C?

We can change the contents of array in the caller function (i.e. test_change()) through callee function (i.e. change) by passing the the value of array to the function (i.e. int *array). This modification can be effective in the caller function without any return statement.

How do you modify a value in an array?

To change the value of all elements in an array:Use the forEach() method to iterate over the array. The method takes a function that gets invoked with the array element, its index and the array itself. Use the index of the current iteration to change the corresponding array element.

Can you replace a value in an array?

Replace an Element in an Array using Array.Use the indexOf() method to get the index of the element you want to replace. Call the Array. splice() method to replace the element at the specific index. The array element will get replaced in place.


1 Answers

You could use the System.Xml.Linq namespace stuff for the easiest to read code. This will load the full file into memory.

XDocument xdoc = XDocument.Load("file.xml");
var element = xdoc.Elements("MyXmlElement").Single();
element.Value = "foo";
xdoc.Save("file.xml");
like image 142
Ben Robbins Avatar answered Oct 25 '22 05:10

Ben Robbins