From the course: .NET Essentials: LINQ for XML

Load data from an XML file - .NET Tutorial

From the course: .NET Essentials: LINQ for XML

Start my 1-month free trial

Load data from an XML file

- [Instructor] Before we can do any work in linked XML we must load the XML data. There are several ways to do that. Here I'm looking at, how to do that on line seven what I'm calling XElement.Load. And you can see that it says Loads Linq.XElement from a file. Now you might be asking yourself why is it called XElement and not XmlElement? And that's due to historic reasons because XmlElement is a name that was available in earlier .net libraries. So for linked XML, they're called XElement, XAttribute and XDocument and other similar names. So I'm calling the load, I need to pass in the file path. So I'm doing some concatenation to get that and I'm working with some helper classes. On line four I'm getting Path.GetDirectoryName and then I'm using a helper class from LINQPad called Util.CurrentQueryPath, and what does that mean? To explain, let's go back to File Explorer and I'm looking at this link file, this one here, load XML data from an XML file so that's in this folder, so this utility class tells me this folder, now the actual XML file that I need is up one directory, it's here in the root. So let's take a look at how I solve that. So I get the current query path that's the location for this file, this one here, and then I go up one folder on line five, and then I specify the file name so here I'm just concatenating those three items together and string them in this variable, which is of type XElement, we'll talk more about that later in this chapter. And then I'm calling Console.WriteLine and passing the XElement and it will output the entire XML that's in that file like this. You can see here in the output window, there's all the XML. Now because I'm using LINQPad, I'll use a helper extension method called dump. For most of the course, I'll be using .Dump like this one of the advantages of this, is it formats information, it will do tables and it does enumerables in a nice fashion and I can also add titles to explain what we're outputting. So now when I run this again, I can see this title here. Other than that the output is identical to Console.WriteLine at least for this example. Now we're saying the basics of loading that XML let's show you some of the other ways we can load the data.

Contents