CSharp - Obtaining Restricted Elements Without Reaching While Ordering and Using Query Expression Syntax

Introduction

In the following example, we query for the document's Book elements but retrieve only the ones whose type attribute is not Illustrator.

Demo

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

class Program/*from  ww  w.  j  a  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 =
                from e in xDocument.Descendants("Book")
                where ((string)e.Attribute("type")) != "Illustrator"
                orderby ((string)e.Element("LastName"))
                select e;
        
              foreach (XElement element in elements)
              {
                Console.WriteLine("Element: {0} : value = {1}",
                  element.Name, element.Value);
              }
    }
}

Result

Related Topic