'c# How to use linq to get xml string by filtering some data?
I want to get xml string by filtering data. For example, I need to filter some students whose sex is female.
I need to use linq to xml to get xml string. The following is my initial xml code and expected xml string.
Initial xml code:
<? 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>
Expected xml string:
<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>
Solution 1:[1]
You can get the xml string like this,
string path = "D:\\test.xml";
XDocument doc = XDocument.Load(path);
doc.Descendants("Student").Where(x =>x.Element("Sex").Value=="male").Remove();
Console.WriteLine(doc.ToString());
Solution 2:[2]
Use the following code.
XDocument doc = XDocument.Load(path);
foreach(var x in doc.Descendants("Student").Where(x => x.Element("Sex").Value == "female"))
{
Console.WriteLine(x.ToString());
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | å¤§é™¸åŒ—æ–¹ç¶²å‹ |
| Solution 2 | Jiachen Li-MSFT |
