WPF C#读取和写入.xml文件错误

时间:2016-04-28 14:50:28

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

所以我试图从.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;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;         
using System.Xml.Linq;      // I included this for XDocument
using System.Xml.XPath;       // I included this because i thought it will fix a problem
  namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    public void loadXML()
    {
        XDocument document = new XDocument();

        if (!File.Exists("MyXmlFile.xml"))
        {

            document.Save("MyXmlFile.xml");
        }
        else
        {
            //We know it exists so we can load it
            document.load("MyXmlFile.xml");
        }

        //Continue to work with document


    }


}
}

1 个答案:

答案 0 :(得分:2)

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

    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
}