no9
no9

Reputation: 6544

LINQ to XML - Update and save a node to XML file

I have an XML file. I want to update (add some nodes) to it. Here is how the code looks:

var xmlDocuments = XDocument.Load(filePath);
var documentElementToEdit = xmlDocuments.Element("Container").Element("Documents").Elements("Document").Where(x => x.Element("GUID").Value == GUID).FirstOrDefault();
missingIndexData1 = new XElement("IndexData");
XElement indexData1 = new XElement("Name", "somename");
XElement indexData2 = new XElement("Value", somevalue);
XElement indexData3 = new XElement("DataType", "3");
XElement indexData4 = new XElement("CreationTime", DateTime.Now.ToString("O"));
XElement indexData5 = new XElement("CreationTimeUTC", DateTime.UtcNow.ToString("O"));
missingIndexData1.Add(indexData1);
missingIndexData1.Add(indexData2);
missingIndexData1.Add(indexData3);
missingIndexData1.Add(indexData4);
missingIndexData1.Add(indexData5);
documentElementToEdit.Element("IndexDatas").Add(missingIndexData1);
documentElementToEdit.Save(filePath);

What this does is that it overwrittes the original XML file with only this document node. How can I update the document node in the original file?

Upvotes: 1

Views: 2656

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499760

What this does is that it overwrittes the original XML file with only this document node. How can I update the document node in the original file?

You need to save the whole document, instead of just the changed element. That will rewrite the whole file, of course, but there's no simple way round that.

xmlDocuments.Save(filePath);

Upvotes: 5

Related Questions