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

问题描述 投票:1回答:1

我正在和学生们一起做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;

    }
c# .net linq linq-to-xml
1个回答
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();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.