XDocument.Save方法中的问题

本文关键字:问题 方法 Save XDocument | 更新日期: 2023-09-27 18:24:30

我正在尝试在现有的XMl文件中插入数据。我有以下代码。

        string file = MapPath("~/XMLFile1.xml");
        XDocument doc;
        //Verify whether a file is exists or not
        if (!System.IO.File.Exists(file))
        {
            doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"),
                new System.Xml.Linq.XElement("Contacts"));
        }
        else
        {
            doc = XDocument.Load(file);
        }
        foreach (var c in MyContactsLst)
        {
            //var contactsElement = new XElement("Contacts",
            var contactsElement = new XElement("Contact",
                                  new XElement("Name", c.FirstOrDefault().DisplayName),
                                  new XElement("PhoneNumber", c.FirstOrDefault().PhoneNumber.ToString()),
                                  new XElement("Email", "abc@abc.com"));
            doc.Root.Add(contactsElement);
            doc.Save(file);
        }

第一个问题出现在代码的第一行,即MapPath("~/XMLFile1.xml");。它给了我一个错误

名称"MapPath"在当前上下文中不存在

第二个问题在doc.Save(file);中,它给了我一个错误

与"System.Xml.Linq.XDocument.Save(System.IO.Stream)"匹配的最佳重载方法具有一些无效参数

我提到了这个问题:如何将数据插入到asp.net中现有的xml文件中?

我正在学习XML。那么,我该如何解决这个问题呢?

XDocument.Save方法中的问题

当前上下文中不存在MapPath的原因是因为它是HttpServerUtility类的一个方法,据我所知,Windows Phone不支持它。

尝试像这样加载XDocument:

XDocument xdocument = XDocument.Load("XMLFile1.xml");

编辑:保存文档时出错。以下是来自相关线程的答案:

using (var storage = IsolatedStorageFile.GetUserStoreForApplication())
{
     using (Stream stream = storage.CreateFile("data.xml"))
     {
         doc.Save(stream);
     }
}

在Kajzer的回答基础上,还有另一种更容易掌握和使用的方法来保存XDocument:

string path = "[some path]";
using (Stream stream = File.Create(path))
{
    doc.Save(stream);
}

只有一个using语句,您只需要System.IO类,因为它同时提供了StreamFile类供您使用,使其成为最简单易懂的解决方案。