2

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>

2 Answers 2

2

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());
Sign up to request clarification or add additional context in comments.

Comments

0

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());
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.