How to Read an XML File With LINQ to XML
It's one of the most common requirements now – read an XML file. There are several methods to opening and parsing an XML file – XPath, XQuery, and LINQ to XML to name a few. I have found that LINQ to XML makes it much easier (and faster) to read and parse an XML file.
I am including a sample project, with xml file, which you can download. LINQ to XML Example.zip (34.93 kb)
All examples use the ObjectDumper class written by Microsoft.
ObjectDumper.cs (5.19 kb)
For the purposes of this example, let's consider an XML file which holds customer contact information, such as the customer name, address, and phone number. In the XML file below, I have tried to demonstrate different formats in the example (using attributes to hold the first/last names, nesting the address information in an address tag). I did this to help demonstrate how easy it is retrieve this information.
Example Customer XML File (samplexml.xml)
<?xml version="1.0" encoding="utf-8" ?>
<Customers>
<Customer>
<Name first="Bob" last="Jones" />
<Address>
<Street>123 Nowhere Street</Street>
<City>Somecity</City>
<State>FL</State>
<Zip>33225</Zip>
</Address>
<Phone>954-555-2233</Phone>
</Customer>
<Customer>
<Name first="Nancy" last="Drew" />
<Address>
<Street>345 Any Avenue</Street>
<City>Somecity</City>
<State>FL</State>
<Zip>33225</Zip>
</Address>
<Phone>754-555-4455</Phone>
</Customer>
<Customer>
<Name first="John" last="Doe" />
<Address>
<Street>567 Nosuch Street</Street>
<City>Miami</City>
<State>FL</State>
<Zip>33552</Zip>
</Address>
<Phone>754-555-6644</Phone>
</Customer>
</Customers>
Let's consider three situations where we need to parse the data in the XML file:
- Retrieving all customers' names
- Retrieving customers in a specific zip code
- Retrieving customers in a specific area code
Note that all examples require the System.XML.LINQ namespace
For our examples, we will be using the following custom class to hold our customer results:
class clsCustNames
{
public string Firstname { get; set; }
public string Lastname { get; set; }
}
LINQ to XML – Example 1 – Get Customer Names
// open the xml document
XDocument xdoc = XDocument.Load("SampleXML.xml");// get a list of the customer names
List<clsCustNames> CustomerNames = (from xml in xdoc.Elements("Customers").Elements("Customer")
select new clsCustNames
{
Firstname = xml.Element("Name").Attribute("first").Value,
Lastname = xml.Element("Name").Attribute("last").Value
}).ToList();// output results
ObjectDumper.Write(CustomerNames);

This first example is pretty straightforward. We use the XDocument object to open the xml file. Next, we get all the Elements that are of type "Customer" { Customers > Customer}. Each Element has it's own list of child Elements. Each Element also has a list of Attributes. In this first example, we use the Attribute filter on the Element "Name" to get the first and last names of the customer.
Finally, notice our call to ToList. This forces the results to return as a List<> of type clsCustNames (the "select new clsCustNames" determines the return type).
For our second example, let's get a list of customers who are in the zip code "33225". We will continue to use the XDocument object (xdoc) for this example.
LINQ to XML – Example 2 – Filtering By Zipcode
// get a list of customers with zip of 33225
List<clsCustNames> ZipFilteredCustNames =
(from xml2 in xdoc.Elements("Customers").Elements("Customer")
where xml2.Element("Address").Element("Zip").Value == "33225"
select new clsCustNames
{
Firstname = xml2.Element("Name").Attribute("first").Value,
Lastname = xml2.Element("Name").Attribute("last").Value
}).ToList();//output results
ObjectDumper.Write(ZipFilteredCustNames);
The second example looks very similar to the first one. Notice, though, we added a "where" clause. This where clause instructs LINQ to only return results which match the criteria – in this case where "Zip" equals "33225". Notice also that the where clause is using the nested element Address > Zip.
For the final example, let's consider the scenario where we only want customers within a specific area code (such as "754").
LINQ to XML – Example 3 – Filtering by Area Code
// get a list of customers with the area code of 754
List<clsCustNames> PhoneFilteredCustNames =
(from xml3 in xdoc.Elements("Customers").Elements("Customer")
where xml3.Element("Phone").Value.StartsWith("754")
select new clsCustNames
{
Firstname = xml3.Element("Name").Attribute("first").Value,
Lastname = xml3.Element("Name").Attribute("last").Value
}).ToList();//output results
Console.WriteLine("");
ObjectDumper.Write(PhoneFilteredCustNames);
You will notice that even with LINQ to XML, we can use standard string extensions (StartsWith) to determine if a record matches the area code "754".
loading...
loading...
No related posts.
Related posts brought to you by Yet Another Related Posts Plugin.
