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");

        }

 

The following relates to this XML from yesterday’s blog. You can get the surrounding code in that blog.
It’s advisable to use the LINQ style of query when possible, but there might be that day where you have a long complicated XPath, and you just want to use with an XElement that you loaded from LINQ. This is how to do that, with several examples.

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 XPathLinqQueries(XElement xelGOT)
        {
            //
            // NOTE: The above is the preferred methodology using LINQ. 
            // In theory, you would use LINQ queries instead of XPATH 
            // queries, but there are two XPATH methods we will demonstrate. 
            //

            //Second Actor using XPath 
            string xpathCharacter2A = "./Characters/Character[2]/Actor";
            var secondActorViaXPathA = xelGOT.XPathSelectElement(xpathCharacter2A).Value;
            Console.WriteLine("Second Actor via XPathA=" + secondActorViaXPathA);


            // NOTE: XPathSelectElement only returns XElements, 
            // so you cannot do count(//Characters) or /Actor/text(). 
            // Instead, you have to use the more general XPathEvaluate.
            // But you must also wrap the xpath with like this: 
            // string(varXPath) 
            // The XPathEvaluate method returns an object that can contain
            // a bool, a double, a string, or an or IEnumerable.

            string xpathCharacter2B = "./Characters/Character[2]/Actor/text()";
            string secondActorViaXpathEval =
                  xelGOT.XPathEvaluate("string(" + xpathCharacter2B + ")") as string;
            Console.WriteLine("Second Actor via XPathB=" + secondActorViaXpathEval);

            string xpathCharacterCount = "count(./Characters/Character)";
            string strCharacterCount =
                  xelGOT.XPathEvaluate("string(" + xpathCharacterCount + ")") as string;
            Console.WriteLine("CharacterCount=" + strCharacterCount);

            double? nullableCharacterCount = xelGOT.XPathEvaluate(xpathCharacterCount) as double?;
            Console.WriteLine("Numeric CharacterCount=" + nullableCharacterCount);

            string xpathCharacter2C = "./Characters/Character";
            IEnumerable results = (IEnumerable)xelGOT.XPathEvaluate(xpathCharacter2C);
            //Loop through Characters 
            Console.WriteLine("\n\n============ Start: XPath Loop through Characters ======");
            foreach (var result in results.Cast())
            {
                Console.WriteLine(
                          " Character=" + result.Element("Name").Value +
                          " Actor=" + result.Element("Actor").Value +
                          " Status=" + result.Attribute("Status")

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


        }

 

Example of how to create XML in memory using LINQ, then how to retrieve elements and attributes from it in the LINQ style.
In a future blog, I will show you how to use XPath, and then LINK Query Expressions.

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

using System;
//using System.Collections;
using System.Collections; //cannot use this one, as it causes clash with IEnumerable
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq; // for XElement
using System.Xml.XPath; // in order to use XPathSelectElement(s)

namespace LINQ_Practice
{
class Program
{
public static string separator = “\n\n——————————————–\n”;
static void Main(string[] args)
{

//LINQ – Language Integrated Query

/*
string xmlInFilename = @”c:\XMLClass\IntroSamples\Flight03.xml”;
// NOTE: we don’t have to instantiate XElement
XElement xelFlight3 = XElement.Load(xmlInFilename);
Console.WriteLine(xelFlight3.ToString());

// Per MSDN article:
// Only use XDocument when you need to add a comment
// or processing instruction at the root level.
XDocument xdocFlight3 = XDocument.Load(xmlInFilename);
Console.WriteLine(separator);
Console.WriteLine(xdocFlight3.ToString());

XElement xelCourse = XElement.Parse(“Complete Guide to XML for Microsoft DevelopersNeal Walters“);
Console.WriteLine(separator);
Console.WriteLine(xelCourse.ToString());

*/

// 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”)
)
)
);

Console.WriteLine(separator);
Console.WriteLine(xelGOT.ToString());

string xmlOutputFilename = @”c:\XMLClass\IntroSamples\GameOfThrones.xml”;
//xelGOT.Save(xmlOutputFilename);

standardLinqQueries(xelGOT);
//XPathLinqQueries(xelGOT);
//queryExpressionsInLinq(xelGOT);

Console.WriteLine(separator);

Console.WriteLine(“\n\n Press enter to end ….”);
Console.ReadLine();
}

public static void standardLinqQueries(XElement xelGOT)
{
// Our XElement is “GameOfThrones” so the
// navigation and XPATH below must start from there

Console.WriteLine(separator);
// NOTE: Don’t put root element in quotes…
string firstActor = xelGOT.Elements(“Characters”).First().Elements(“Character”).First().Elements(“Actor”).First().Value;
Console.WriteLine(“First Actor=” + firstActor);

//illustrate ElementAt method – zero-based
string secondActor = xelGOT.Elements(“Characters”).Elements(“Character”).ElementAt(1).Elements(“Actor”).First().Value;
Console.WriteLine(“Second Actor=” + secondActor);

//illustrate Skip method
string thirdActor = xelGOT.Elements(“Characters”).Elements(“Character”).Skip(2).Elements(“Actor”).First().Value;
Console.WriteLine(“Third Actor=” + thirdActor);

//Loop through Characters
Console.WriteLine(“\n\n============ Start: Loop through Characters ======”);
foreach (XElement xelChar in xelGOT.Elements(“Characters”).Elements(“Character”))
{
Console.WriteLine(
” Character=” + xelChar.Element(“Name”).Value +
” Actor=” + xelChar.Element(“Actor”).Value +
” Status=” + xelChar.Attribute(“Status”).Value
);
}
Console.WriteLine(“============ End: Loop through Characters ======\n\n”);

}

}
}