.NET FAQs Unleashed!
 
    
    

How to search XML documents using LINQ?

Say we have the following XML document and we want to search a value from here using LINQ.

 

<Students>

  <Student name=”Elena”>

     <Id>405</Id>

  </Students>

  <Student name=”John”>

     <Id>406</Id>

  </Students>

</Students>

 

Now if you want to search an attribute value here with an attribute value of name set to “John”, you may use the following code:

 

XDocument studentXml = CreateStudentListXml();

 

Console.WriteLine(“Search the attribute with value John”);

var theQuery = from student in

                studentXml.Element(“Students”).Elements(“Customer”)            

                where student.Attribute(“name”).Value == “John”

                select student;

XElement elem = theQuery.SingleOrDefaul();

 

If(elem != null)

{

   Console.WriteLine(elem);

}

else

{

  Console.WriteLine(“No student like that”);

}

 

Silverlight DOM Parser   Parents of Child Elements   XML document using LINQ   XML document using XDocument and XElement?   Attributes and XAttribute    Read XML using XPathDocument    Search XML using LINQ   Serialize and deserialize XML    Empty XML element   Advantage of XmlReader and XmlWriter   Well formed XML VS Valid XML    XHTML VS HTML   Define XML  

More Interview Questions.....