【问题标题】:Issue in XDocument.Save MethodXDocument.Save 方法中的问题
【发布时间】:2017-08-15 01:50:15
【问题描述】:

我正在尝试在现有 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)' 的最佳重载方法匹配有一些无效参数

这个问题我已经参考How to insert data into an existing xml file in asp.net?

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

【问题讨论】:

    标签: c# xml windows-phone-7 windows-phone-8 linq-to-xml


    【解决方案1】:

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

    【讨论】:

    • @Kajzar 嘿,谢谢您的回复。我已经检查过了。但现在问题出在 Save 方法上。它给了我一个错误。
    • 'System.Xml.Linq.XDocument.Save(System.IO.Stream)'的最佳重载方法匹配有一些无效参数
    • 好的,告诉我你是如何使用 Save 方法的(你调用该方法的邮政编码)。请注意,您应该删除“字符串文件”。
    • doc.Save("~/XMLFile1.xml");通过使用这种方法,我正在保存我的 XML 文件。
    • 但是我已经在我的 windows phone 项目中创建了我的 XMLFile1.xml 文件。我只想在这个文件中插入数据
    【解决方案2】:

    除了 Kajzer 的回答之外,这里还有另一种可能更容易掌握和用于保存 XDocument 的替代方法:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-11
      • 2012-05-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多