如何修复System.Xml.Linq.XContainer.Element(...)返回null

时间:2019-06-01 21:24:27

标签: c# xml wpf linq

我正在尝试向XML文件中写入数据和从中读取数据,编写工作正常,但是在读取时我得到System.Xml.Linq.XContainer.Element(...)返回null。错误。我首先要通过表单将用户的输入保存为XML,然后从XML中获取数据并在listview中显示

书写代码

private void Btn_addproduct_Click(object sender, RoutedEventArgs e)
        {
            i++;
            XDocument doc = XDocument.Load("C:\\Users\\karam\\source\\repos\\KanbanBoard\\bin\\Debug\\tester.xml");
            doc.Root.Add(new XElement("Project",
                new XElement("ProjectId", i),
                new XElement("ProjectTitle", projectTitle.Text),
                new XElement("ProjectDescription", projectDescription.Text),
                new XElement("StartDate", startDate.Text),
                new XElement("EndDate", endDate.Text),
                new XElement("ToDoLimit", toDoLimit.Text),
                new XElement("WorkInProgressLimit", workInProgressLimit.Text),
                new XElement("DoneLimit", doneLimit.Text)
                ));
            doc.Save("C:\\Users\\karam\\source\\repos\\KanbanBoard\\bin\\Debug\\tester.xml");
        }

阅读代码

 private void Btn_productlist_Click(object sender, RoutedEventArgs e)
        {
            XDocument doc = XDocument.Load("C:\\Users\\karam\\source\\repos\\KanbanBoard\\bin\\Debug\\tester.xml");
            var result=doc.Descendants("Projects").Select(x=>new
            {
                projectid = x.Element("ProjectId").Value,
                projecttitle = x.Element("ProjectTitle").Value,
                projectdescription = x.Element("ProjectDescription").Value,
                startdate = x.Element("StartDate").Value,
                enddate = x.Element("EndDate").Value,
                todolimit = x.Element("ToDoLimit").Value,
                workinprogresslimit = x.Element("WorkInProgressLimit").Value,
                donelimit = x.Element("DoneLimit").Value,
            });


            Projectlistview.ItemsSource = result;

        }

1 个答案:

答案 0 :(得分:0)

Descendants(name)方法返回给定文档的后代元素的集合。 (只有具有匹配名称的元素才会包含在集合中)

之所以给出null,是因为它找不到名称为Projects的元素。

 XDocument doc = XDocument.Load("C:\\Users\\karam\\source\\repos\\KanbanBoard\\bin\\Debug\\tester.xml");
 var result = doc.Descendants("Projects").Select(x => new //Should be Project
 //rest of the code