How to get specific element from XML using LINQ or C#

Gani_tpt 1,806 Reputation points
2022-01-04T16:56:44.377+00:00

I have the XML file. I want to get only specific element from the XML.

For example, ,

I want to get

TotResults="5000" , TotCount="45" and EmpStatus="Active"

from the below XML element.

How do i get using LINQ or simple C# code...?

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<SearchCriteria TotPages="250" TotResults="5000" TotCount="45">
<SearchResults>
<Employee EmpId="AXZ2022101">
<DateJoined></DateJoined>
<EmpStatus>Active</EmpStatus>
<Country>USA</Country>
<Phone>009974e635236</Phone>
</Employee>
</SearchResults>
</SearchCriteria>
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,420 questions
{count} votes

Accepted answer
  1. Yitzhak Khabinsky 25,211 Reputation points
    2022-01-04T17:55:21.457+00:00

    Please try the following solution.

    It is using LINQ to XML API. It is available in the .Net Framework since 2007.

    c#

    void Main()
    {
        const string filename = @"e:\Temp\GaniTPT.xml";
    
        XDocument xdoc = XDocument.Load(filename);
    
        Console.WriteLine("TotResults: {0}, TotCount: {1}, EmpStatus: {2}"
            , xdoc.Element("SearchCriteria").Attribute("TotResults").Value
            , xdoc.Element("SearchCriteria").Attribute("TotCount").Value
            , xdoc.Descendants("EmpStatus").FirstOrDefault().Value);
    }
    

    Output

    TotResults: 5000, TotCount: 45, EmpStatus: Active
    
    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. P a u l 10,406 Reputation points
    2022-01-04T17:24:27.437+00:00

    If you copy your XML to your clipboard, create a file in your project called SearchCriteria.cs, go to "Edit > Paste Special > Paste Xml As Classes" and that'll generate a class structure for the XML in your clipboard. Then you'll be able to just use XmlSerializer to parse the text:

    using System.Xml.Serialization;
    
    const string xml = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
     <SearchCriteria TotPages=""250"" TotResults=""5000"" TotCount=""45"">
     <SearchResults>
     <Employee EmpId=""AXZ2022101"">
     <DateJoined></DateJoined>
     <EmpStatus>Active</EmpStatus>
     <Country>USA</Country>
     <Phone>009974e635236</Phone>
     </Employee>
     </SearchResults>
     </SearchCriteria>";
    
    XmlSerializer serializer = new XmlSerializer(typeof(SearchCriteria));
    
    StringReader sr = new StringReader(xml);
    
    SearchCriteria criteria = (SearchCriteria)serializer.Deserialize(sr);
    
    Console.WriteLine(criteria.TotResults);
    Console.WriteLine(criteria.TotCount);
    Console.WriteLine(criteria.SearchResults.Employee.EmpStatus);