CSharp - Obtaining Restricted Elements Without Reaching

Introduction

We use the Where operator.

We cast the FirstName element to a string to get its value for the comparison to "PHP".

Demo

using System;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;

class Program/*  w ww.  ja v  a 2  s  .c om*/
{
    static void Main(string[] args){
        XDocument xDocument = new XDocument(
          new XElement("Books",
            new XElement("Book",
              new XAttribute("type", "Author"),
              new XElement("FirstName", "Joe"),
              new XElement("LastName", "Ruby")),
            new XElement("Book",
              new XAttribute("type", "Editor"),
              new XElement("FirstName", "PHP"),
              new XElement("LastName", "Python"))));
        
        IEnumerable<XElement> elements = xDocument
          .Descendants("Book")
          .Where(e => ((string)e.Element("FirstName")) == "PHP");
        
        foreach (XElement element in elements)
        {
          Console.WriteLine("Element: {0} : value = {1}",
            element.Name, element.Value);
        }
    }
}

Result

Related Topic