Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read and edit an XML file using C#?

Tags:

c#

.net

xml

How can I open and edit an existing XML file? I would like to modify some values like:

<address>myaddr</address>

For example, I would like to put loreal instead if myaddr. I am working in C#. I would appreciate if you can show me some code.

like image 412
hello Avatar asked Feb 23 '11 07:02

hello


3 Answers

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";
}
doc.Save("test.xml");
like image 54
Darin Dimitrov Avatar answered Nov 15 '22 18:11

Darin Dimitrov


Let's say you have the following XML file:

<root>
    <address>myaddr</address>
</root>

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

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

For more information read the following:

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

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

like image 43
Alex Shtof Avatar answered Nov 15 '22 20:11

Alex Shtof


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

Read those resources:

  • Introduction to XML Document Object Model
  • Introduction to Linq-to-XML: simple XML parsing

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

like image 1
marc_s Avatar answered Nov 15 '22 18:11

marc_s