6

I have the following code, which successfully writes to an XML file. However, it overwrites each time because of the tagRegistry.Save() call being made. How can I add a new XElement to the 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

2 回答 2

13

尝试这个:

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);
        }
    }
}
于 2013-07-15T23:52:08.327 回答
2

你的File.Exists电话可能是错误的。您将文件存储到隔离存储,但从当前运行目录中读取。所以你总是陷入困境else,每次都写一个新文件。

于 2013-07-16T00:05:18.677 回答