使用LINQ在XML文件中查找对象

时间:2019-02-21 18:39:00

标签: c# .net linq linq-to-xml

我正在与学生们进行CRUD,并且试图找到一个使用LINQ的学生,但是我不想使用列表,所以我想直接处理XML文件。我该怎么办?

我的XML文件是:

<?xml version="1.0"?>
<ArrayOfStudent xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Student>
      <IDstudent>56</IDstudent>
      <Name>da</Name>
      <Surname>he</Surname>
  </Student>
</ArrayOfStudent>

它可以将我的XML加载到列表中并执行LINQ,但我想以一种有效的方式做到这一点。

    public Student FindStudent(string id)
    {
        List<Student> LStudent = GetAll();
        Student student = LStudent.Where(e => e.IDstudent == id).FirstOrDefault();
        return student;

    }

1 个答案:

答案 0 :(得分:1)

您可以先查看如何加载到xDocument中,然后使用Linq:

using System.Xml.Linq;
using System.Linq;

class Program
{
    public static string FindStudent(XDocument xDoc, string id)
    {
        //this gets the list of Student elements in the document
        var students = xDoc.Elements().First().Elements("Student");

        //this gets the one with the requested id
        //throws an 'InvalidOperationException' if 0 OR more than 1 element found
        var studentById = students.Single(c => c.Element("IDstudent").Value == id);

        //return a string that you already are able to transform into a Student object??
        return studentById.ToString();  
    }

    static void Main(string[] args)
    {
        //Load into an xDocument from file
        XDocument xDoc = XDocument.Load(@"Path\To\Test.xml");

        Console.WriteLine(FindStudent(xDoc, "3"));
        Console.ReadLine();
    }
}