使用 LINQ 在 XML 文件中查找对象
Find object in XML file with LINQ
我正在对学生进行 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;
}
您可以看看加载到 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();
}
}
我正在对学生进行 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;
}
您可以看看加载到 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();
}
}