How to filter the values from xml file and print it to text file in C#

Viewed 65
<MasterCode>
    <Uid>119</Uid>
    <Name>Juan Gabriel MONTE</Name>
    <Category>LastName</Category>
  </MasterCode>
<MasterCode>
    <Uid>120</Uid>
    <Name>Atilla SELEK</Name>
    <Category>FirstName</Category>
  </MasterCode>
 <MasterCode>
    <Uid>121</Uid>
    <Name>barbosa filisa</Name>
    <Category>LastName</Category>
  </MasterCode>

This is an example of my xml file. i want to filter only the names that comes under the category last name. how to filter it and print the names in text file with C#?. Please help Thank u in advance.

1 Answers

You can try with XDocument and Linq

var xmlDoc = XDocument.Load("XMLFile2.xml");

var result = xmlDoc.Descendants("MasterCode")
    .Where(element => (string)element.Element("Category") == "LastName")
    .Select(x => x.Element("Name").Value)
    .ToList();
Related