c# 如何使用linq通过过滤一些数据来获取xml字符串?

Jac*_*SFT 2 c# xml linq

我想通过过滤数据来获取xml字符串。例如,我需要过滤一些性别为女性的学生。

我需要使用 linq to xml 来获取 xml 字符串。以下是我的初始 xml 代码和预期的 xml 字符串。

初始 xml 代码:

 <? xml version="1.0" encoding="utf-8"?>
    <School>
    <Student>
          <Name>Test1</Name>
          <Birthday>1997-02-23</Birthday>
          <Id>1001</Id>
          <Sex>male</Sex>
          <ClassId>01</ClassId>
          <Scorevalue>Net Revenue</Scorevalue>
    </Student>
    <Student>
          <Name>Test1</Name>
          <Birthday>1998-02-21</Birthday>
          <Id>1002</Id>
          <Sex>female</Sex>
          <ClassId>02</ClassId>
          <Scorevalue>Net Revenue</Scorevalue>
    </Student>
    <Student>
          <Name>Test1</Name>
          <Birthday>1997-02-24</Birthday>
          <Id>1004</Id>
          <Sex>male</Sex>
          <ClassId>03</ClassId>
          <Scorevalue></Scorevalue>
    </Student>
    </School>
Run Code Online (Sandbox Code Playgroud)

预期的 xml 字符串:

<School>
  <Student>
    <Name>Test1</Name>
    <Birthday>1998-02-21</Birthday>
    <Id>1002</Id>
    <Sex>female</Sex>
    <ClassId>02</ClassId>
    <Scorevalue>Net Revenue</Scorevalue>
  </Student>
</School>
Run Code Online (Sandbox Code Playgroud)

小智 5

使用以下代码。

        XDocument doc = XDocument.Load(path);
        foreach(var x in doc.Descendants("Student").Where(x => x.Element("Sex").Value == "female"))
        {
            Console.WriteLine(x.ToString());
        }
Run Code Online (Sandbox Code Playgroud)