简体   繁体   中英

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM