繁体   English   中英

如何在c#Windows 8 App中更新现有XML文件的元素?

[英]How can I update an element of an existing XML file in c# Windows 8 App?

我在Assets文件夹中有一个XML文件。 尝试使用Linq读取文件时,我没有任何问题。 但是,当我要写入该文件时,没有看到错误,并且目标元素从未更新。

我的代码如下:

private static readonly string mealsXMLPath = Path.Combine(Package.Current.InstalledLocation.Path, "Assets/meals.xml");
    private XDocument loadedData;

在构造函数中,我具有初始化代码:

loadedData = XDocument.Load(mealsXMLPath);

我用来更新现有元素值的实际代码在这里

public async void UpdateQuantity(Dictionary<int, int> orderdetails)
        {
            XDocument xmlFile = XDocument.Load(mealsXMLPath);
            foreach(var key in orderdetails.Keys)
            {
                XElement upd = (from order in xmlFile.Descendants("Meal")
                                where order.Element("ID").Value == key.ToString()
                                select order).Single();
                upd.Element("Avaibility").Value = (Convert.ToInt32(upd.Element("Avaibility").Value) - orderdetails[key]).ToString();


            }
        }

我尝试了其他内置方法,例如xdoc.save("path")xml...Create(..) 。但是似乎没有一个方法在C#Windows 8应用程序中正常工作。

您必须将文档保存到可写目录中:

using (var stream = await (await ApplicationData.Current.LocalFolder.CreateFileAsync(System.IO.Path.GetFileName(mealsXMLPath))).OpenAsync(FileAccessMode.ReadWrite))
{
    xmlFile.Save(stream.AsStreamForWrite());
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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