Add XElement to Xdocument

I have the following code that successfully writes to an XML file. However, it is overwritten every time due to the call to tagRegistry.Save (). How to add a new XElement to an existing file? At the moment, the file is simply overwritten.

public void saveTag() { if (File.Exists("/tagRegistry.xml")) { XElement tagRegistry = XElement.Load("/tagRegistry.xml"); XElement newTag = new XElement("Tag", new XElement("tag", stringUid), new XElement("name", desiredName), new XElement("latitude", latitude), new XElement("longitude", longitude)); tagRegistry.Add(newTag); using (var storage = IsolatedStorageFile.GetUserStoreForApplication()) { using (Stream stream = storage.CreateFile("/tagRegistry.xml")) { tagRegistry.Save(stream); } } } else { XDocument tagRegistry = new XDocument(new XElement("SmartSafe")); tagRegistry.Element("SmartSafe").Add(new XElement("Tag", new XElement("tag", stringUid), new XElement("name", desiredName), new XElement("latitude", latitude), new XElement("longitude", longitude))); using (var storage = IsolatedStorageFile.GetUserStoreForApplication()) { using (Stream stream = storage.CreateFile("/tagRegistry.xml")) { tagRegistry.Save(stream); } } } } 
+4
source share
2 answers

Try the following:

 public void saveTag() { using (var storage = IsolatedStorageFile.GetUserStoreForApplication()) { XDocument document; XElement tagRegistry = null; if (storage.FileExists("/tagRegistry.xml")) { using(var stream = storage.OpenFile("/tagRegistry.xml", FileMode.Open)) { document = XDocument.Load(stream); } tagRegistry = document.Descendants("SmartSafe").FirstOrDefault(); } else { document = new XDocument(); } if(tagRegistry == null) { tagRegistry = new XElement("SmartSafe"); document.Add(tagRegistry); } XElement newTag = new XElement("Tag", new XElement("tag", stringUid), new XElement("name", desiredName), new XElement("latitude", latitude), new XElement("longitude", longitude)); tagRegistry.Add(newTag); using (Stream stream = storage.CreateFile("/tagRegistry.xml")) { document.Save(stream); } } } 
+11
source

Maybe your call to File.Exists wrong. You store the file in isolated storage, but you are reading it from the current current directory. Thus, you always fall into the else block and write a new file each time.

+2
source

Source: https://habr.com/ru/post/1491542/


All Articles