Csharp/C#教程:将新XElement添加到Xdocument分享


将新XElement添加到Xdocument

我有以下代码,它成功写入XML文件。 但是,由于正在进行tagRegistry.Save()调用,它每次都会覆盖。 如何在现有文件中添加新的XElement? 目前文件只是被覆盖。

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

试试这个:

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

您的File.Exists调用可能是错误的。 您将文件存储到独立存储,但从当前运行目录读入。 所以你总是落入else块并且每次都写一个新文件。

上述就是C#学习教程:将新XElement添加到Xdocument分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1024854.html

(0)
上一篇 2022年1月8日
下一篇 2022年1月8日

精彩推荐