[ACCEPTED]-How can I read and edit an XML file using C#?-xml

Accepted answer
Score: 11

You could use the XDocument class:

var doc = XDocument.Load("test.xml");
var address = doc.Root.Element("address");
if (address != null)
    address.Value = "new value";


Score: 4

Let's say you have the following XML file:


And 9 you want to do the replacement. There are 8 many options. Some are explicitly modifying 7 XML, others are translating your XML to 6 classes, modifying and translating back 5 to XML (serialization). Here is one of the 4 ways do do it:

XDocument doc = XDocument.Load("myfile.xml");
doc.Root.Element("address").Value = "new address"

For more information read 3 the following:

  1. LINQ to XML is the technique 2 I used here - http://msdn.microsoft.com/en-us/library/bb387098.aspx

  2. XML serialization is another 1 technique - http://msdn.microsoft.com/en-us/library/182eeyhh.aspx

Score: 1

Yes, that's totally possible - and quite 4 easily, too.

Read those resources:

and a great many more - just 3 search for "Intro Linq-to-XML" or 2 "Intro XMLDocument" - you'll get 1 plenty of links to good articles and blog posts.

More Related questions