【问题标题】:Error in WPF when trying to read and write from a file using C#尝试使用 C# 从文件中读取和写入时出现 WPF 错误
【发布时间】:2016-04-28 14:50:27
【问题描述】:

所以我试图从/in .xml 文件中读取和写入,我得到了这个错误:

'System.Xml.Linq.XDocument' does not contain a definition for 'load' and no extension method 'load' accepting a first argument of type 'System.Xml.Linq.XDocument' could be found (are you missing a using directive or an assembly reference?) 

换行:

document.load("MyXmlFile.xml");

代码示例:

using System.Xml.Linq;      // I included this for XDocument
using System.Xml.XPath;     // I included this because I thought it will fix a problem

public partial class MainWindow : Window
{
    public MainWindow() => InitializeComponent();

    public void LoadXML()
    {
        var document = new XDocument();

        if (!File.Exists("MyXmlFile.xml"))
             document.Save("MyXmlFile.xml");
        else document.load("MyXmlFile.xml");
    }
}

【问题讨论】:

    标签: c# xml wpf visual-studio-2010


    【解决方案1】:

    你必须稍微改变你的方法:

    if (!File.Exists("MyXmlFile.xml"))
    {
        document.Save("MyXmlFile.xml");
    }
    else
    {
        //We know it exists so we can load it
        document = XDocument.Load("MyXmlFile.xml"); // changed
    }
    
    //Continue to work with document
    

    【讨论】:

    • 将其更改为加载,我收到一个新错误:无法使用实例引用访问成员“System.Xml.Linq.XDocument.Load(string)”;改为使用类型名称来限定它
    • 当我第二次尝试运行它时,我得到一个减弱的说法:缺少根元素。有什么建议吗?
    • @C-PROG,这是因为您的文档是空的并且不包含任何元素,如果您添加一些元素(即 )一切都会正常工作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-30
    相关资源
    最近更新 更多