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.
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");
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:
LINQ to XML is the technique I used here - http://msdn.microsoft.com/en-us/library/bb387098.aspx
XML serialization is another technique - http://msdn.microsoft.com/en-us/library/182eeyhh.aspx
Yes, that's totally possible - and quite easily, too.
Read those resources:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With