LINQ/XML Query Expressions Examples

The following relates to the previous two blogs. You can get the surrounding code in that C# LINQ/XML example blog.

LINQ can run against different data sources, including XML an SQL. So once you learn how to write the query expressions as shown below, you can switch back and forth between them with ease.

This is a sample from Complete Guide to XML for Microsoft Developers (Udemy Course).


            // GOT = Game of Thrones (data) 
            XElement xelGOT =
              new XElement("GameOfThrones",
                 new XElement("Characters",
                     new XElement("Character",
                         new XAttribute("Status", "deceased"),
                         new XElement("Name", "Daenerys Targaryen"),
                         new XElement("Actor", "Emilia Clarke")
                         ),
                     new XElement("Character",
                         new XAttribute("Status", "living"),
                         new XElement("Name", "Jon Snow"),
                         new XElement("Actor", "Kit Harrington")
                         ),
                     new XElement("Character",
                         new XAttribute("Status", "living"),
                         new XElement("Name", "Tyrion Lannister"),
                         new XElement("Actor", "Peter Dinklage")
                         )
                      ),
                 new XElement("Cities",
                     new XElement("City",
                         new XElement("Name", "King's Landing"),
                         new XElement("Location", "The Crownlands, Westeros")
                         ),
                     new XElement("City",
                         new XElement("Name", "Braavos"),
                         new XElement("Location", "The Free Cities, Essos")
                         ),
                     new XElement("City",
                         new XElement("Name", "Lannisport"),
                         new XElement("Location", "The Westerlands, The Seven Kingdoms")
                         )
                      )
                   );

 


        
        public static void queryExpressionsInLinq(XElement xelGOT)
        {
            Console.WriteLine(separator); 
            // Get second living character (sorted by character name) 
            // Error: at least one object must implement IComparable 
            string secondLivingCharacter =
                (from xchar in xelGOT.Elements("Characters").First().Elements("Character")
                 where (string)xchar.Attribute("Status").Value == "living"
                 orderby xchar.Element("Name").Value ascending  
                 select xchar).ElementAt(1).Element("Name").Value;
            Console.WriteLine("secondLivingCharacter=" + secondLivingCharacter); 

            // Get all the living characters 
            // Note the better way to test for a value equals something... 
            // the .Equals() method does not require casting 
            var results =   
                (from xchar in xelGOT.Elements("Characters").First().Elements("Character")
                where xchar.Attribute("Status").Value.Equals("living")
                select xchar);

            // Loop and show multiple matches 
            Console.WriteLine("\n\n============ Start: Query Living Characters ======");
            foreach (var result in results)
            {
                Console.WriteLine(
                          " Character=" + result.Element("Name").Value +
                          " Actor=" + result.Element("Actor").Value +
                          " Status=" + result.Attribute("Status").Value

                     );  ;
            }
            Console.WriteLine("============ End: Loop through Living Characters ======\n\n");

        }


 

Uncategorized  

Leave a Reply