2

我正在尝试在现有 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。那么,我该如何解决呢?

4

2 回答 2

3

之所以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);
     }
}
于 2013-07-24T06:13:29.887 回答
0

添加到 Kajzer 的答案中,这是另一种可能更容易掌握和用于保存的替代方法XDocument

string path = "[some path]";

using (Stream stream = File.Create(path))
{
    doc.Save(stream);
}

只有一个using语句,您只需要System.IO该类,因为它提供了StreamFile类供您使用 - 使其成为最直接和最容易理解的解决方案。

于 2017-08-14T17:50:15.767 回答